从GridView中导出Excel的公共方法(使用DataSet来传递值)
- 格式:doc
- 大小:124.00 KB
- 文档页数:17
将DataGridView中的数据导出至Excel(亲测成功)一、建立一个静态方法public static void ExportAsExcel(DataGridView dgv){OutputAsExcelFile(DGVHelper.DataGridViewToTable(dgv));}二、把DataGridView中的数据转换到DataTable中///<summary>///将DataGridView中的数据转换为DataTable包含隐藏列///</summary>///<param name="dgv"></param>///<returns></returns>public static DataTable DataGridViewToTable(DataGridView dgv){DataTable dt=new DataTable();//循环列标题名称,处理了隐藏的行不显示for(int count=0;count<dgv.Columns.Count;count++){if(dgv.Columns[count].Visible==true){dt.Columns.Add(dgv.Columns[count].HeaderText.ToString());}}//循环行,处理了隐藏的行不显示for(int count=0;count<dgv.Rows.Count;count++){DataRow dr=dt.NewRow();int curr=0;for(int countsub=0;countsub<dgv.Columns.Count;countsub++){if(dgv.Columns[countsub].Visible==true){if(dgv.Rows[count].Cells[countsub].Value!=null){dr[curr]=dgv.Rows[count].Cells[countsub].Value.ToString();}else{dr[curr]="";}curr++;}}dt.Rows.Add(dr);}return dt;}三、把DataTable中的数据导出到Excel中public static void OutputAsExcelFile(DataTable dt){if(dt.Rows.Count<=0){MessM.PromptInfo("提示","无数据!");return;}SaveFileDialog s=new SaveFileDialog{Title="保存Excel文件",Filter="Excel文件(*.xls)|*.xls",FilterIndex=1};if(s.ShowDialog()==DialogResult.OK)filePath=s.FileName;elsereturn;DTExportToExcel(dt);}///<summary>///第二步:导出dataTable到Excel///</summary>///<param name="dt"></param>private static void DTExportToExcel(DataTable dt){//第二步:导出dataTable到Excellong rowNum=dt.Rows.Count;//行数int columnNum=dt.Columns.Count;//列数Excel.Application m_xlApp=new Excel.Application{DisplayAlerts=false,//不显示更改提示Visible=false};Excel.Workbooks workbooks=m_xlApp.Workbooks;Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1try{string[,]datas=new string[rowNum+1,columnNum];for(int i=0;i<columnNum;i++)//写入字段datas[0,i]=dt.Columns[i].Caption;//Excel.Range range=worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[1, columnNum]);Excel.Range range=m_xlApp.Range[worksheet.Cells[1,1],worksheet.Cells[1, columnNum]];range.Interior.ColorIndex=15;//15代表灰色range.Font.Bold=true;range.Font.Size=10;int r=0;for(r=0;r<rowNum;r++){for(int i=0;i<columnNum;i++){object obj=dt.Rows[r][dt.Columns[i].ToString()];datas[r+1,i]=obj==null?"":"'"+obj.ToString().Trim();//在obj.ToString()前加单引號是为了防止自己主动转化格式}Application.DoEvents();//加入进度条}//Excel.Range fchR=worksheet.get_Range(worksheet.Cells[1,1], worksheet.Cells[rowNum+1,columnNum]);Excel.Range fchR=m_xlApp.Range[worksheet.Cells[1,1],worksheet.Cells[rowNum+1, columnNum]];fchR.Value2=datas;worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
c#datagridview导出到excel ⽅法⼀:添加dll引⽤右击选择你所在的项⽬的“引⽤”,选择“添加引⽤”。
弹出“添加引⽤”对话框。
选择“COM”选项卡。
选择“Microsoft Excel 11.0 Object Library”单击“确定”按钮。
代码public static bool ExportForDataGridview(DataGridView gridView, string fileName, bool isShowExcle) {//建⽴Excel对象Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); try{if (app == null){return false;}app.Visible = isShowExcle;Workbooks workbooks = app.Workbooks;_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);Sheets sheets = workbook.Worksheets;_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);if (worksheet == null){return false;}string sLen = "";//取得最后⼀列列名char H = (char)(64 + gridView.ColumnCount / 26);char L = (char)(64 + gridView.ColumnCount % 26);if (gridView.ColumnCount < 26){sLen = L.ToString();}else{sLen = H.ToString() + L.ToString();}//标题string sTmp = sLen + "1";Range ranCaption = worksheet.get_Range(sTmp, "A1");string[] asCaption = new string[gridView.ColumnCount];for (int i = 0; i < gridView.ColumnCount; i++){asCaption[i] = gridView.Columns[i].HeaderText;}ranCaption.Value2 = asCaption;//数据object[] obj = new object[gridView.Columns.Count];for (int r = 0; r < gridView.RowCount - 1; r++){for (int l = 0; l < gridView.Columns.Count; l++){if (gridView[l, r].ValueType == typeof(DateTime)){obj[l] = gridView[l, r].Value.ToString();}else{obj[l] = gridView[l, r].Value;}}string cell1 = sLen + ((int)(r + 2)).ToString();string cell2 = "A" + ((int)(r + 2)).ToString();Range ran = worksheet.get_Range(cell1, cell2);ran.Value2 = obj;}//保存workbook.SaveCopyAs(fileName);workbook.Saved = true;}finally{//关闭erControl = false;app.Quit();}return true;}⽅法⼆⽤流保存成xls⽂件. 这种⽅法⽐较好,不⽤引⽤Excel组件. 下⾯是具体例⼦,可以参考using System.IO;////// 另存新档按钮///private void SaveAs() //另存新档按钮导出成Excel{SaveFileDialog saveFileDialog = new SaveFileDialog();saveFileDialog.Filter = "Execl files (*.xls)|*.xls";saveFileDialog.FilterIndex = 0;saveFileDialog.RestoreDirectory = true;saveFileDialog.CreatePrompt = true;saveFileDialog.Title = "Export Excel File To";saveFileDialog.ShowDialog();Stream myStream;myStream = saveFileDialog.OpenFile();//StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));string str = "";try{//写标题for (int i = 0; i < dgvAgeWeekSex.ColumnCount; i++){if (i > 0){str += "\t";}str += dgvAgeWeekSex.Columns[i].HeaderText;}sw.WriteLine(str);//写内容for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++){string tempStr = "";for (int k = 0; k < dgvAgeWeekSex.Columns.Count; k++){if (k > 0){tempStr += "\t";}tempStr += dgvAgeWeekSex.Rows[j].Cells[k].Value.ToString(); }sw.WriteLine(tempStr);}sw.Close();myStream.Close();}catch (Exception e){MessageBox.Show(e.ToString());}finally{sw.Close();myStream.Close();}}。
ListView导出到Excel的方法今天写了一个把ListView中的内容导出到Excel的公共方法,传入一个类型为ListView的参数,就可以了,还是满方便的!大家给点意见吧!public static void ExpToExcel(ListView listviewname){if (listviewname.Items.Count == 0) return;Excel.Application excel = new Excel.Application();Excel.Workbooks workbooks = excel.Workbooks;Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Sheets worksheets = workbook.Worksheets;Excel.Worksheet sheet = (Excel.Worksheet) worksheets.get_Item(1);excel.Visible = true;Excel.Range range;excel.Cells.Select();excel.Cells.RowHeight = 30;excel.Cells.Font.Size = 10;excel.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;int rowPos = 2;range = excel.get_Range(sheet.Cells[rowPos,1],sheet.Cells[rowPos,1]);range.Select();for(int i=1;i<=listviewname.Columns.Count;i++){range = excel.get_Range(sheet.Cells[rowPos,i],sheet.Cells[rowPos,i]);range.Borders.LineStyle = 1; = "华文仿宋";range.Font.Size = 16;range.Font.Bold = true;range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;range.ColumnWidth = 18;sheet.Cells[rowPos,i] = listviewname.Columns[i-1].Text.ToString();}rowPos++;foreach(ListViewItem item in listviewname.Items){for(int i=1;i<=listviewname.Columns.Count;++i){range = excel.get_Range(sheet.Cells[rowPos,i],sheet.Cells[rowPos,i]);range.Borders.LineStyle = 1; = "华文仿宋";range.Font.Size = 12;range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;sheet.Cells[rowPos,i] = item.SubItems[i-1].Text;}rowPos++;}}。
C#DataGridView导出excel的⼏种⽅法第⼀种、⾸先本form上游datagridview的控件及数据,再建⼀个button控件作为导出按钮,在按钮click事件中写⼊以下代码此乃数据集的⽅式,即先将数据放⼊数据集表⾥作为对象与excel⼀⼀对应//保存⽂件对话框SaveFileDialog sfd = new SaveFileDialog();sfd.Filter = "Excel⽂件|*.xlsx|Word⽂件|*.docx";sfd.FilterIndex = 0;if (sfd.ShowDialog() == DialogResult.OK){string search = "select * from 旧备件表 where(0=0)";if (this.textBox1.Text.Length > 0){search = search + " and 物料编码=" + "'" + textBox1.Text + "'";}if (this.textBox2.Text.Length > 0){search = search + " and 设备号=" + "'" + textBox2.Text + "'";}if (this.textBox3.Text.Length > 0){search = search + " and 物料描述 like" + "'%" + textBox3.Text + "%'";//实现物料描述的模糊查询}if (this.textBox4.Text.Length > 0){search = search + " and 备件序列号 like" + "'%" + textBox4.Text + "%'";//实现备件序列号的模糊查询}//调⽤导出Excel的⽅法,传⼊DataTable数据表和路径SqlDataAdapter sda = new SqlDataAdapter(search, DataBase.GetSqlConnection());System.Data.DataTable dt = new System.Data.DataTable();//将数据库中查到的数据填充到DataTable数据表sda.Fill(dt);ExportExcel(dt, sfd.FileName);}}void ExportExcel(System.Data.DataTable dt, string filepath){//创建Excel应⽤程序类的⼀个实例,相当于从电脑开始菜单打开ExcelApplicationClass xlsxapp = new ApplicationClass();//新建⼀张Excel⼯作簿Workbook wbook = xlsxapp.Workbooks.Add(true);//第⼀个sheet页Worksheet wsheet = (Worksheet)wbook.Worksheets.get_Item(1);//将DataTable的列名显⽰在Excel表第⼀⾏for (int i = 0; i < dt.Columns.Count; i++){//注意Excel表的⾏和列的索引都是从1开始的wsheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;}//遍历DataTable,给Excel赋值for (int i = 0; i < dt.Rows.Count; i++){for (int j = 0; j < dt.Columns.Count; j++){//从第⼆⾏第⼀列开始写⼊数据wsheet.Cells[i + 2, j + 1] = dt.Rows[i][j];}}//保存⽂件wbook.SaveAs(filepath);//释放资源xlsxapp.Quit();}第⼆种、此乃直接将datagridview⾥的数据⼀⼀导出放⼊excel指定的单元格⾥。
1.Public Function Export2Excel(ByVal LV_object As ListView, SheetName As String,OnlySelect As Boolean, ExcelColAutoFit As Boolean, PageHengxiang As Boolean)2.'ListView控件输出数据到Excel3.Dim ErrHnd As Long4.On Error GoTo ErrHnd5. Dim Row As Long6. Dim Col As Long7. Dim objExl As Excel.Application '声明对象变量8. Set objExl = New Excel.Application '初始化对象变量9. With objExl10. .SheetsInNewWorkbook = 1 '将新建的工作薄数量设为111. .Workbooks.Add '增加一个工作薄12. .Sheets(.Sheets.Count).Name = SheetName '修改工作薄名称13. .Sheets(SheetName).Select '选中工作薄<book1>14. 'ListView标题行获取15. .Selection.NumberFormatLocal = "@" '设置格式为文本16. For Col = 1 To LV_object.ColumnHeaders.Count17. .Cells(1, Col) = LV_object.ColumnHeaders(Col).Text18. Next Col19.20. '循环读取ListView控件的数据21. ViewWsd.ProgressBox.Visible = True22. For Row = 1 To LV_object.ListItems.Count '行23. If OnlySelect Then '仅输出选择的行24. If LV_object.ListItems(Row).Checked = True Then25. .Cells(Row + 1, 1) = LV_object.ListItems(Row).Text '第一列关键字26. For Col = 1 To LV_object.ColumnHeaders.Count - 1 '后面所有列27. .Cells(Row + 1, Col + 1) =LV_object.ListItems(Row).SubItems(Col)28. Next Col29. End If30. Else31. If LV_object.ListItems(Row).Checked = True Then32. .Cells(Row + 1, 1) = LV_object.ListItems(Row).Text '第一列关键字33. For Col = 1 To LV_object.ColumnHeaders.Count - 1 '后面所有列34. .Cells(Row + 1, Col + 1) =LV_object.ListItems(Row).SubItems(Col)35. Next Col36. End If37. End If38. '调用进程条39. 'Call ProgressStatus(LV_object.ListItems.Count, Row)40. DoEvents41. Next Row42. .Rows("1:1").Select '选中第一行43. .Selection.Font.Bold = True '设为粗体44. = "Verdana"45. .Selection.Font.Size = 11 '设置字体大小46.47. .Rows("2:" & LV_object.ListItems.Count + 1).Select '选中第一行外所有有数据的行48. .Selection.Font.Bold = False '设为粗体49. .Selection.Font.Size = 11 '设置字体大小50. = "Verdana"51.52. If ExcelColAutoFit Then .Cells.EntireColumn.AutoFit '自动调整列宽53.54. .ActiveWindow.SplitRow = 1 '拆分第一行55. .ActiveWindow.SplitColumn = 0 '拆分列56. .ActiveWindow.FreezePanes = True '固定拆分57. If PageHengxiang Then58. '必装打印机先59. .ActiveSheet.PageSetup.Orientation = xlLandscape '纸张横向60. Else61. '必装打印机先62. .ActiveSheet.PageSetup.Orientation = xlPortrait '纸张纵向63. End If64. .ActiveSheet.PageSetup.PrintTitleRows = "$1:$1" '设置打印固定行65. '必装打印机先66. .ActiveSheet.PageSetup.RightFooter = "&""Verdana,加粗""&11 QunFun Studio" & Format(Now, "yyyy年mm月dd日 hh:MM:ss")67. .ActiveWindow.View = xlNormalView '设置显示方式68. .ActiveWindow.Zoom = 100 '设置显示大小69.70. .Application.IgnoreRemoteRequests = False71. .Visible = True '使EXCEL可见72. .Application.WindowState = xlMaximized 'EXCEL的显示方式为最大化73. .ActiveWindow.WindowState = xlMaximized '工作薄显示方式为最大化74. .SheetsInNewWorkbook = 3 '将默认新工作薄数量改回3个75. End With76. Set objExl = Nothing '清除对象77.ViewWsd.ProgressBox.Visible = False78.Exit Function79.80.ErrHnd:81. If Err.Number = 1004 Then82. MsgBox "Excel输出错误(" & Err.Number & ")" & vbCrLf & Err.Description &vbCrLf & "本机没有安装打印机,页面设置功能被忽略。
C#将DataGridView中显⽰的数据导出到Excel(.xls和.xlsx格式)—NPOI 前⾔ 本地数据库表中有46785条数据,测试正常 初次运⾏程序第⼀次导出,⽤时在4-5s左右;此后再导出⽤时在2-3s左右;可能与缓存有关 ⽀持导出为.xls和.xlsx格式 可以⾃定义字体和字号 exe测试⽂件下载地址: 密码:test实现步骤⼀、安装NPOI右键项⽬→ "管理NuGet程序包" →搜索NPOI →安装⼆、创建类using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using erModel;using erModel;//导出xls格式⽤HSSFusing erModel;//导出xlsx格式⽤XSSFusing System.IO;using System.Runtime.InteropServices;using System.Diagnostics;using NPOI.SS.Util;namespace ExportToExcel{public class ExportDgvToExcel{#region NPOI DataGridView 导出 EXCEL/// <summary>/// NPOI DataGridView 导出 EXCEL/// 03版Excel-xls最⼤⾏数是65536⾏,最⼤列数是256列/// 07版Excel-xlsx最⼤⾏数是1048576⾏,最⼤列数是16384列/// </summary>/// <param name="fileName">默认保存⽂件名</param>/// <param name="dgv">DataGridView</param>/// <param name="fontname">字体名称</param>/// <param name="fontsize">字体⼤⼩</param>public void ExportExcel(string fileName, DataGridView dgv, string fontname, short fontsize){IWorkbook workbook;ISheet sheet;Stopwatch sw = null;//判断datagridview中内容是否为空if (dgv.Rows.Count == 0){MessageBox.Show("DataGridView中内容为空,请先导⼊数据!", "提⽰", MessageBoxButtons.OK, MessageBoxIcon.Warning); return;}//保存⽂件string saveFileName = "";SaveFileDialog saveFileDialog = new SaveFileDialog();saveFileDialog.DefaultExt = "xls";saveFileDialog.Filter = "Excel⽂件(*.xls)|*.xls|Excel⽂件(*.xlsx)|*.xlsx";saveFileDialog.RestoreDirectory = true;saveFileDialog.Title = "Excel⽂件保存路径";saveFileDialog.FileName = fileName;MemoryStream ms = new MemoryStream(); //MemoryStreamif (saveFileDialog.ShowDialog() == DialogResult.OK)//**程序开始计时**//sw = new Stopwatch();sw.Start();saveFileName = saveFileDialog.FileName;//检测⽂件是否被占⽤if (!CheckFiles(saveFileName)){MessageBox.Show("⽂件被占⽤,请关闭⽂件" + saveFileName);workbook = null;ms.Close();ms.Dispose();return;}}else{workbook = null;ms.Close();ms.Dispose();}//*** 根据扩展名xls和xlsx来创建对象string fileExt = Path.GetExtension(saveFileName).ToLower();if (fileExt == ".xlsx"){workbook = new XSSFWorkbook();}else if (fileExt == ".xls"){workbook = new HSSFWorkbook();}else{workbook = null;}//***//创建Sheetif (workbook != null){sheet = workbook.CreateSheet("Sheet1");//Sheet的名称}else{return;}//设置单元格样式ICellStyle cellStyle = workbook.CreateCellStyle();//⽔平居中对齐和垂直居中对齐cellStyle.Alignment = erModel.HorizontalAlignment.Center;cellStyle.VerticalAlignment = erModel.VerticalAlignment.Center;//设置字体IFont font = workbook.CreateFont();font.FontName = fontname;//字体名称font.FontHeightInPoints = fontsize;//字号font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;//字体颜⾊cellStyle.SetFont(font);//添加列名IRow headRow = sheet.CreateRow(0);for (int i = 0; i < dgv.Columns.Count; i++){//隐藏⾏列不导出if (dgv.Columns[i].Visible == true){headRow.CreateCell(i).SetCellValue(dgv.Columns[i].HeaderText);headRow.GetCell(i).CellStyle = cellStyle;}}//根据类型写⼊内容for (int rowNum = 0; rowNum < dgv.Rows.Count; rowNum++){///跳过第⼀⾏,第⼀⾏为列名IRow dataRow = sheet.CreateRow(rowNum + 1);for (int columnNum = 0; columnNum < dgv.Columns.Count; columnNum++){int columnWidth = sheet.GetColumnWidth(columnNum) / 256; //列宽//隐藏⾏列不导出if (dgv.Rows[rowNum].Visible == true && dgv.Columns[columnNum].Visible == true) {//防⽌⾏列超出Excel限制if (fileExt == ".xls"){//03版Excel最⼤⾏数是65536⾏,最⼤列数是256列if (rowNum > 65536){MessageBox.Show("⾏数超过Excel限制!");return;}if (columnNum > 256){MessageBox.Show("列数超过Excel限制!");return;}}else if (fileExt == ".xlsx"){//07版Excel最⼤⾏数是1048576⾏,最⼤列数是16384列if (rowNum > 1048576)MessageBox.Show("⾏数超过Excel限制!");return;}if (columnNum > 16384){MessageBox.Show("列数超过Excel限制!");return;}}ICell cell = dataRow.CreateCell(columnNum);if (dgv.Rows[rowNum].Cells[columnNum].Value == null){cell.SetCellType(CellType.Blank);}else{if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Int32")){cell.SetCellValue(Convert.ToInt32(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.String")){cell.SetCellValue(dgv.Rows[rowNum].Cells[columnNum].Value.ToString());}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Single")){cell.SetCellValue(Convert.ToSingle(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Double")){cell.SetCellValue(Convert.ToDouble(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Decimal")){cell.SetCellValue(Convert.ToDouble(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.DateTime")){cell.SetCellValue(Convert.ToDateTime(dgv.Rows[rowNum].Cells[columnNum].Value).ToString("yyyy-MM-dd"));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.DBNull")){cell.SetCellValue("");}}//设置列宽IRow currentRow;if (sheet.GetRow(rowNum) == null){currentRow = sheet.CreateRow(rowNum);}else{currentRow = sheet.GetRow(rowNum);}if (currentRow.GetCell(columnNum) != null){ICell currentCell = currentRow.GetCell(columnNum);int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;if (columnWidth < length){columnWidth = length + 10; //设置列宽数值}}sheet.SetColumnWidth(columnNum, columnWidth * 256);//单元格样式dataRow.GetCell(columnNum).CellStyle = cellStyle;}}}//保存为Excel⽂件workbook.Write(ms);FileStream file = new FileStream(saveFileName, FileMode.Create);workbook.Write(file);file.Close();workbook = null;ms.Close();ms.Dispose();//**程序结束计时**//sw.Stop();double totalTime = sw.ElapsedMilliseconds / 1000.0;MessageBox.Show(fileName + " 导出成功\n耗时" + totalTime + "s", "提⽰", MessageBoxButtons.OK, rmation); }#endregion#region 检测⽂件是否被占⽤/// <summary>/// 判定⽂件是否打开/// </summary>[DllImport("kernel32.dll")]public static extern IntPtr _lopen(string lpPathName, int iReadWrite);[DllImport("kernel32.dll")]public static extern bool CloseHandle(IntPtr hObject);public const int OF_READWRITE = 2;public const int OF_SHARE_DENY_NONE = 0x40;public readonly IntPtr HFILE_ERROR = new IntPtr(-1);/// <summary>/// 检测⽂件被占⽤/// </summary>/// <param name="FileNames">要检测的⽂件路径</param>/// <returns></returns>public bool CheckFiles(string FileNames){if (!File.Exists(FileNames)){//⽂件不存在return true;}IntPtr vHandle = _lopen(FileNames, OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR){//⽂件被占⽤return false;}//⽂件没被占⽤CloseHandle(vHandle);return true;}#endregion}}三、调⽤private void btnExport_Click_1(object sender, EventArgs e){ExportDgvToExcel export = new ExportDgvToExcel();export.ExportExcel("", dgv, "宋体", 11);//默认⽂件名,DataGridView控件的名称,字体,字号}。
DataGirdµ¼³öEXCELµÄ¼¸¸ö·½·¨£¨WebControl£©using System;using System.Data;using System.Text;using System.Web;using System.Web.UI;using System.Diagnostics;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;using System.Data.SqlClient;using System.Collections;namespace bookstore{/// <summary>/// myExcel µÄժҪ˵Ã÷¡£/// </summary>public class myExcel{public myExcel(){}/// <summary>/// ½«DATAGRIDµ¼³öΪEXCELÎļþ·½·¨Ò»,/// ²ÎÊýÊÇ:Òªµ¼³öµÄDATAGRIDµÄIDºÍÒª±£´æÏÂÀ´µÄEXCELÎļþÃû/// </summary>/// <param name="myPage">page</param>/// <param name="dg">datagrid</param>/// <param name="name">filename</param>private void OutExcel(Page myPage,DataGrid dg,string name) {HttpResponse Response;Response=myPage.Response;string name1="attachment;filename="+name+".xls";dg.Visible=true;Response.Clear();Response.Buffer= true;Response.Charset="GB2312";Response.AppendHeader("Content-Disposition",name1);Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312" );Response.ContentType ="application/ms-excel";dg.EnableViewState = false;System.IO.StringWriter oStringWriter = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);dg.RenderControl(oHtmlTextWriter);Response.Write(oStringWriter.ToString());Response.End();}/// <summary>/// ½«DATAGRIDµ¼³öΪEXCELÎļþ·½·¨¶þ,/// ²ÎÊýÊÇ:Òªµ¼³öµÄDATAGRIDµÄIDºÍÒª±£´æÏÂÀ´µÄEXCELÎļþÃû/// </summary>/// <param name="myPage">page</param>/// <param name="ctl">datagrid</param>/// <param name="filename">filename</param>public void ExportToExcel(Page myPage,DataGrid ctl,string filename) {HttpResponse Response;Response=myPage.Response;bool CurrCtlVisible=ctl.Visible;ctl.Visible=true;Response.AppendHeader("Content-Disposition","attachment;filename="+filename+".xls");Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");Response.ContentType = "application/ms-excel";ctl.Page.EnableViewState = false;System.IO.StringWriter tw = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);ctl.RenderControl(hw);Response.Write(tw.ToString());Response.End();ctl.Page.EnableViewState = true;ctl.Visible=CurrCtlVisible;}private void DgOutExcel(Page myPage,DataGrid dg,string name){HttpResponse Response;Response=myPage.Response;string name1="attachment;filename="+name+".xls";dg.Visible=true;Response.Clear();Response.Buffer= true;Response.Charset="GB2312";Response.AppendHeader("Content-Disposition",name1);Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312" );Response.ContentType ="application/ms-excel";dg.EnableViewState = false;System.IO.StringWriter oStringWriter = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);dg.RenderControl(oHtmlTextWriter);Response.Write(oStringWriter.ToString());Response.End();}#region µ¼³öEXCEL£¬ÓÃDATASETpublic string myExportString(DataGrid DG,DataSet ds){string HTstring="<table><tr>";string Fieldstring="";ArrayList myAL=new ArrayList();string sRows="<tr>";for(int i=0;i<DG.Columns.Count;i++){HTstring+="<td>"+DG.Columns[i].HeaderText+"</td>";Fieldstring+="<td>"+((System.Web.UI.WebControls.BoundColumn)(DG.Columns[i])).DataField+"</td>";myAL.Add(((System.Web.UI.WebControls.BoundColumn)(DG.Columns[i])).DataField);}for(int k=0;k<ds.Tables[0].Rows.Count;k++){foreach(string field in myAL){sRows+= "<td>"+ds.Tables[0].Rows[k][field]+"</td>";}sRows+="</tr>";}HTstring+="</tr>"+sRows+"</table>";return HTstring;}public void SaveToExcel(Page myPage, string myExportString,stringmyFileName){HttpResponse resp;resp=myPage.Response;resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");resp.AppendHeader("Content-Disposition","attachment;filename="+myFileName+".xls");resp.ContentType="application/ms-excel"; resp.Write(myExportString);resp.End();//resp.Clear();//resp.Close();}public void Export(DataGrid myDG,DataTable dt,HttpResponse response){// clean up response objectresponse.Clear();response.Charset = "";response.Charset = "UTF-8";// response.ContentEncoding = System.Text.Encoding.Default;response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312" );// set response object's mime type// response.ContentType = "application/vnd.ms-excel";response.AppendHeader("Content-Disposition","attachment;filename=m ytest.xls");System.IO.StringWriter sw = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);DataGrid dg = new DataGrid();dg.AllowPaging = false;dg.AllowSorting = false;ArrayList myAL=new ArrayList();for(int i=0;i<myDG.Columns.Count;i++){// dg.Columns.AddAt(i,myDG.Columns[i]);// dg.Columns[i].HeaderText=myDG.Columns[i].HeaderText;myAL.Add(((System.Web.UI.WebControls.BoundColumn)(myDG.Columns[i]) ).DataField);for(int k=0;k<dt.Columns.Count;k++){foreach(string field in myAL){if(dt.Columns[i].ColumnName==field){dt.Columns[i].ColumnName=myDG.Columns[i].HeaderText;}}}}dg.DataSource = dt;dg.ShowHeader = true;dg.HeaderStyle.BackColor = System.Drawing.Color.DarkGray;dg.HeaderStyle.ForeColor = System.Drawing.Color.White;dg.HeaderStyle.Font.Bold = true;dg.AlternatingItemStyle.BackColor = System.Drawing.Color.LightGray;dg.DataBind();dg.RenderControl(htw);response.Write(sw.ToString());response.End();}#endregion}}。
1.#region DataGridView数据显示到Excel2./// <summary>3./// 打开Excel并将DataGridView控件中数据导出到Excel4./// </summary>5./// <param name="dgv">DataGridView对象</param>6./// <param name="isShowExcle">是否显示Excel界面</param>7./// <remarks>8./// add com "Microsoft Excel 11.0 Object Library"9./// using Excel=Microsoft.Office.Interop.Excel;10./// </remarks>11./// <returns> </returns>12.public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)13.{14.if(dgv.Rows.Count == 0)15.return false;16.//建立Excel对象17.Excel.Application excel = new Excel.Application();18.excel.Application.Workbooks.Add(true);19.excel.Visible = isShowExcle;20.//生成字段名称21.for(int i = 0; i < dgv.ColumnCount; i++)22.{23.excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;24.}25.//填充数据26.for(int i = 0; i < dgv.RowCount - 1; i++)27.{28.for(int j = 0; j < dgv.ColumnCount; j++)29.{30.if(dgv[j, i].ValueType == typeof(string))31.{32.excel.Cells[i + 2, j + 1] = "'"+ dgv[j, i].Value.ToString();33.}34.else35.{36.excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();38.}39.}40.return true;41.}42.#endregion43.44.#region DateGridView导出到csv格式的Excel45./// <summary>46./// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成Excel打开。
把WinForm的DataGridView的数据导出到Excel三种方法导出WinForm的DataGridView数据到Excel有多种方法,下面将详细介绍三种常用的方法:方法一:使用Microsoft.Office.Interop.Excel库这是一种常用的方法,使用Microsoft.Office.Interop.Excel库可以直接操作Excel文件。
首先,需要在项目中添加对Microsoft Office 的引用。
然后,可以按照以下步骤导出数据:1. 创建一个Excel应用程序对象:```csharpusing Excel = Microsoft.Office.Interop.Excel;Excel.Application excelApp = new Excel.Application(;```2.创建一个工作簿对象:```csharpExcel.Workbook workbook =excelApp.Workbooks.Add(Type.Missing);```3.创建一个工作表对象:```csharpExcel.Worksheet worksheet = workbook.ActiveSheet;```4. 将DataGridView中的数据导入到Excel中:```csharpfor (int i = 0; i < dataGridView.Rows.Count; i++)for (int j = 0; j < dataGridView.Columns.Count; j++)worksheet.Cells[i + 1, j + 1] =dataGridView.Rows[i].Cells[j].Value.ToString(;}```5. 保存Excel文件并关闭Excel应用程序:```csharpworkbook.SaveAs("路径\\文件名.xlsx");excelApp.Quit(;```方法二:使用OpenXml库OpenXml是一种用于操作Office文件的开放式标准。
从GridView中导出Excel的公共方法(使用DataSet来传递值)一:前台(“按钮Export的id:btnExport”)二:按钮Export的事件protected void btnExport_Click(object sender, EventArgs e){if (ViewState["downloadDS"] == null){string str = "Please make sure there is query data before click export button!";ScriptManager.RegisterStartupScript(Page, this.GetType(), "Close","<script>alert('" + str + "')</script>", false);return;}string filename = "EmpDetails_Reprot.xls";Page.Response.Clear();PublicFun pf = new PublicFun();bool success = pf.ExcelExport(Page.Request, Page.Response, (DataSet)ViewState["downloadDS"], filename); //传递DataSet值if (!success){Response.Write("Download Failure !");}Page.Response.End();}三:后台代码1:在PublicFun类中public bool ExcelExport(HttpRequest _Request, HttpResponse _Response, DataSet ds, string filename){bool result = false;try{//先处理下载的文件名filename//判断filename是否为空if (string.IsNullOrEmpty(filename)){filename = "Temp.xls";}else{if (filename.Length > 4){//获取上传文件路径中的文件及后缀(ToUpper:字符串转换大写ToLower:转换小写)if (filename.Substring(stIndexOf('.')).ToUpper() !=".XLS"){filename = filename.Trim() + ".xls";}}else{filename = filename.Trim() + ".xls";}}ExportExcel exp = new ExportExcel();//删除已有的filename文件名if (exp.DeleteFile(ExportPath + filename) == true){//编辑Excel文件的内容,如果编辑Excel成功,就可以下载if (exp.ExcelExport(ds, ExportPath, filename) == true){//下载Excel文件if (exp.DownloadFile(_Request, _Response, filename, ExportPath+ filename, 1024000) == true){result = true;}exp.DeleteFile(ExportPath + filename);}}}catch (Exception ex){throw ex;}return result;}2:在ExportExcel类中using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;using System.Data;using System.Threading;using CSharpJExcel.Jxl;using CSharpJExcel.Jxl.Write;using CSharpJExcel.Jxl.Format;using System.Globalization;//删除已有的filename文件名public bool DeleteFile(string path){bool result = true;if (System.IO.File.Exists(path)){try{System.IO.File.Delete(path);result = true;}catch{result = false;}}return result;}//编辑Excel文件的内容public bool ExcelExport(DataSet rts, string path, string filename){bool result = true;try{string file = path + filename;//Filestream只可以进行以字节为单位原始数据流进行读写操作(实例化一个文件流,如果FileMode是Create的话, 那么当实例产生的时候就会同时创建一个Bytes为0的File。
)FileStream sf = new FileStream(file, FileMode.Create);//StreamWriter可以进行以字符为单位的数据读写操作StreamWriter sw = new StreamWriter(sf);//读取excel的时候一开始设置好读取的编码方式就能解决中文乱码(关键代码,解决中文乱码).WorkbookSettings ws = new WorkbookSettings();ws.setLocale(new CultureInfo("en"));//创建工作薄,WritableWorkbook workbook = Workbook.createWorkbook(sf, ws);//是workbook设置一定颜色setColourRGB(Colour c,int r,int g,int b)workbook.setColourRGB(Colour.LIME, 0xff, 0, 0);//定义单元格格式(用于表格标题)WritableCellFormat cf = newWritableCellFormat(WritableWorkbook.ARIAL_10_PT);// 是否换行cf.setWrap(true);// 线条cf.setBorder(CSharpJExcel.Jxl.Format.Border.ALL, BorderLineStyle.THIN);// 水平对齐cf.setAlignment(Alignment.CENTRE);int indsheet = 1;foreach (DataTable dt in rts.Tables){//DataTable 对象的集合中每个表的TableName。
string sheetname = dt.TableName;//判断字符串sheetname是否为空if (string.IsNullOrEmpty(sheetname)){//Replace()功能将一个字符串中指定个数的字符串替换为另一个字符串sheetname = filename.Replace(".xls", "") + indsheet.ToString();}//导出表数据到Excel的sheetwriteSheet(workbook, sheetname, indsheet, dt);indsheet++;}workbook.write();workbook.close();//重新写入流sw.Write(sf);//是清空缓存区的垃圾sw.Flush();sw.Close();sf.Close();}catch{result = false;}return result;}// 下载Excel文件(_Request: Page.Request对象,_Response: Page.Response 对象,_fileName: 下载文件名,_fullPath: 带文件名下载路径,_speed 每秒允许下载的字节数)public bool DownloadFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed){try{//保存在媒体滋盘上(在计算机创建目录)FileStream myFile = new FileStream(_fullPath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite);//以文件的全路对应的字符串和文件打开模式来初始化FileStream文件流实例BinaryReader br = new BinaryReader(myFile);try{//重要:续传必须。
支持两个续传的响应头Accept-Ranges、ETag(Accept-Ranges:响应头,向客户端指明,此进程支持可恢复下载.实现后台智能传输服务(BITS),值为:bytes;ETag:响应头,用于对客户端的初始(200)响应,以及来自客户端的恢复请求,必须为每个文件提供一个唯一的ETag值(可由文件名和文件最后被修改的日期组成),这使客户端软件能够验证它们已经下载的字节块是否仍然是最新的。
)_Response.AddHeader("Accept-Ranges", "bytes");//关闭页面缓冲_Response.Buffer = false;long fileLength = myFile.Length;long startBytes = 0;double pack = 10240; //分快读取,每快10K bytes//毫秒数:读取下一数据块的时间间隔int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;//Request.Headers[]:这个方法防止刷新重复提交.(客户端报文头中通过Range报文头来标识客户期望的下载位置,Range:续传的起始位置,即已经下载到客户端的字节数,值如:bytes=1474560- )if (_Request.Headers["Range"] != null){//---如果是续传请求,则获取续传的起始位置,即已经下载到客户端的字节数--- //重要:续传必须,表示局部范围响应。