C# WinForm导出Excel方法介绍
.NET开发人员首选的方法,通过COM组件调用Office软件本身来实现文件的创建和读写,但是数据量较大的时候异常缓慢;如下代码所示已经做了优化,将一个二维对象数组赋值到一个单元格区域中(下面的代码中只能用于导出列数不多于26列的数据导出): Office PIA 复制代码 代码如下: public static void ExportToExcel(DataSet dataSet,string outputPath) { Excel.ApplicationClass excel = new Excel.ApplicationClass(); Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing); int sheetIndex = 0; foreach (System.Data.DataTable dt in dataSet.Tables) { object[,] data = new object[dt.Rows.Count + 1,dt.Columns.Count]; for (int j = 0; j < dt.Columns.Count; j++) { data[0,j] = dt.Columns[j].ColumnName; } for (int j = 0; j < dt.Columns.Count; j++) { for (int i = 0; i < dt.Rows.Count; i++) { data[i + 1,j] = dt.Rows[i][j]; } } string finalColLetter = string.Empty; string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; [DllImport("user32.dll",SetLastError = true)] static void KillSpecialExcel(Excel.Application app) 文件流 这种方法的效率明显高于第一种,而且也不需要安装Office,但是导出的xls文件并不符合Excel的格式标准,在打开生成的xls文件时会提示:The file you are trying to open is in a different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. 复制代码 代码如下: public static void ExportToExcel(System.Data.DataSet ds,string path) { StreamWriter sw = null; try { long totalCount = ds.Tables[0].Rows.Count; sw = new StreamWriter(path,false,Encoding.Unicode); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { sb.Append(ds.Tables[0].Columns[i].ColumnName + "t"); } sb.Append(Environment.NewLine); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { for (int j = 0; j < ds.Tables[0].Columns.Count; j++) { sb.Append(ds.Tables[0].Rows[i][j].ToString() + "t"); } sb.Append(Environment.NewLine); } sw.Write(sb.ToString()); sw.Flush(); } catch (IOException ioe) { throw ioe; } finally { if (sw != null) { sw.Close(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |