C# 导出 Excel 的各种方法总结

C# 导出 Excel 的各种方法总结

第一种:使用 Microsoft.Office.Interop.Excel.dll

首先需要安装 office 的 excel,然后再找到 Microsoft.Office.Interop.Excel.dll 组件,添加到引用。

  1 public void ExportExcel(DataTable dt)
  2         {
  3             if (dt != null)
  4             {
  5                 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
  6 
  7                 if (excel == null)
  8                 {
  9                     return;
 10                 }
 11 
 12                 //设置为不可见,操作在后台执行,为 true 的话会打开 Excel
 13                 excel.Visible = false;
 14 
 15                 //打开时设置为全屏显式
 16                 //excel.DisplayFullScreen = true;
 17 
 18                 //初始化工作簿
 19                 Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.Workbooks;
 20 
 21                 //新增加一个工作簿,Add()方法也可以直接传入参数 true
 22                 Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
 23                 //同样是新增一个工作簿,但是会弹出保存对话框
 24                 //Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
 25 
 26                 //新增加一个 Excel 表(sheet)
 27                 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
 28 
 29                 //设置表的名称
 30                 worksheet.Name = dt.TableName;
 31                 try
 32                 {
 33                     //创建一个单元格
 34                     Microsoft.Office.Interop.Excel.Range range;
 35 
 36                     int rowIndex = 1;       //行的起始下标为 1
 37                     int colIndex = 1;       //列的起始下标为 1
 38 
 39                     //设置列名
 40                     for (int i = 0; i < dt.Columns.Count; i++)
 41                     {
 42                         //设置第一行,即列名
 43                         worksheet.Cells[rowIndex, colIndex + i] = dt.Columns[i].ColumnName;
 44 
 45                         //获取第一行的每个单元格
 46                         range = worksheet.Cells[rowIndex, colIndex + i];
 47 
 48                         //设置单元格的内部颜色
 49                         range.Interior.ColorIndex = 33;
 50 
 51                         //字体加粗
 52                         range.Font.Bold = true;
 53 
 54                         //设置为黑色
 55                         range.Font.Color = 0;
 56 
 57                         //设置为宋体
 58                         range.Font.Name = "Arial";
 59 
 60                         //设置字体大小
 61                         range.Font.Size = 12;
 62 
 63                         //水平居中
 64                         range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
 65 
 66                         //垂直居中
 67                         range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
 68                     }
 69 
 70                     //跳过第一行,第一行写入了列名
 71                     rowIndex++;
 72 
 73                     //写入数据
 74                     for (int i = 0; i < dt.Rows.Count; i++)
 75                     {
 76                         for (int j = 0; j < dt.Columns.Count; j++)
 77                         {
 78                             worksheet.Cells[rowIndex + i, colIndex + j] = dt.Rows[i][j].ToString();
 79                         }
 80                     }
 81 
 82                     //设置所有列宽为自动列宽
 83                     //worksheet.Columns.AutoFit();
 84 
 85                     //设置所有单元格列宽为自动列宽
 86                     worksheet.Cells.Columns.AutoFit();
 87                     //worksheet.Cells.EntireColumn.AutoFit();
 88 
 89                     //是否提示,如果想删除某个sheet页,首先要将此项设为fasle。
 90                     excel.DisplayAlerts = false;
 91 
 92                     //保存写入的数据,这里还没有保存到磁盘
 93                     workbook.Saved = true;
 94 
 95                     //设置导出文件路径
 96                     string path = HttpContext.Current.Server.MapPath("Export/");
 97 
 98                     //设置新建文件路径及名称
 99                     string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
100 
101                     //创建文件
102                     FileStream file = new FileStream(savePath, FileMode.CreateNew);
103 
104                     //关闭释放流,不然没办法写入数据
105                     file.Close();
106                     file.Dispose();
107 
108                     //保存到指定的路径
109                     workbook.SaveCopyAs(savePath);
110 
111                     //还可以加入以下方法输出到浏览器下载
112                     FileInfo fileInfo = new FileInfo(savePath);
113                     OutputClient(fileInfo);
114                 }
115                 catch(Exception ex)
116                 {
117 
118                 }
119                 finally
120                 {
121                     workbook.Close(false, Type.Missing, Type.Missing);
122                     workbooks.Close();
123 
124                     //关闭退出
125                     excel.Quit();
126 
127                     //释放 COM 对象
128                     Marshal.ReleaseComObject(worksheet);
129                     Marshal.ReleaseComObject(workbook);
130                     Marshal.ReleaseComObject(workbooks);
131                     Marshal.ReleaseComObject(excel);
132 
133                     worksheet = null;
134                     workbook = null;
135                     workbooks = null;
136                     excel = null;
137 
138                     GC.Collect();
139                 }
140             }
141         }
View Code
 1 public void OutputClient(FileInfo file)
 2         {
 3             HttpContext.Current.Response.Buffer = true;
 4 
 5             HttpContext.Current.Response.Clear();
 6             HttpContext.Current.Response.ClearHeaders();
 7             HttpContext.Current.Response.ClearContent();
 8 
 9             HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
10 
11             //导出到 .xlsx 格式不能用时,可以试试这个
12             //HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
13 
14             HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));
15 
16             HttpContext.Current.Response.Charset = "GB2312";
17             HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
18 
19             HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
20 
21             HttpContext.Current.Response.WriteFile(file.FullName);
22             HttpContext.Current.Response.Flush();
23 
24             HttpContext.Current.Response.Close();
25         }
View Code

第一种方法性能实在是不敢恭维,而且局限性太多。首先必须要安装 office(如果计算机上面没有的话),而且导出时需要指定文件保存的路径。也可以输出到浏览器下载,当然前提是已经保存写入数据。

第二种:使用 Aspose.Cells.dll

这个 Aspose.Cells 是 Aspose 公司推出的导出 Excel 的控件,不依赖 Office,商业软件,收费的。

可以参考:http://www.cnblogs.com/xiaofengfeng/archive/2012/09/27/2706211.html#top

 1 public void ExportExcel(DataTable dt)
 2         {
 3             try
 4             {
 5                 //获取指定虚拟路径的物理路径
 6                 string path = HttpContext.Current.Server.MapPath("DLL/") + "License.lic";
 7 
 8                 //读取 License 文件
 9                 Stream stream = (Stream)File.OpenRead(path);
10 
11                 //注册 License
12                 Aspose.Cells.License li = new Aspose.Cells.License();
13                 li.SetLicense(stream);
14 
15                 //创建一个工作簿
16                 Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
17 
18                 //创建一个 sheet 表
19                 Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
20 
21                 //设置 sheet 表名称
22                 worksheet.Name = dt.TableName;
23 
24                 Aspose.Cells.Cell cell;
25 
26                 int rowIndex = 0;   //行的起始下标为 0
27                 int colIndex = 0;   //列的起始下标为 0
28 
29                 //设置列名
30                 for (int i = 0; i < dt.Columns.Count; i++)
31                 {
32                     //获取第一行的每个单元格
33                     cell = worksheet.Cells[rowIndex, colIndex + i];
34 
35                     //设置列名
36                     cell.PutValue(dt.Columns[i].ColumnName);
37 
38                     //设置字体
39                     cell.Style.Font.Name = "Arial";
40 
41                     //设置字体加粗
42                     cell.Style.Font.IsBold = true;
43 
44                     //设置字体大小
45                     cell.Style.Font.Size = 12;
46 
47                     //设置字体颜色
48                     cell.Style.Font.Color = System.Drawing.Color.Black;
49 
50                     //设置背景色
51                     cell.Style.BackgroundColor = System.Drawing.Color.LightGreen;
52                 }
53 
54                 //跳过第一行,第一行写入了列名
55                 rowIndex++;
56 
57                 //写入数据
58                 for (int i = 0; i < dt.Rows.Count; i++)
59                 {
60                     for (int j = 0; j < dt.Columns.Count; j++)
61                     {
62                         cell = worksheet.Cells[rowIndex + i, colIndex + j];
63 
64                         cell.PutValue(dt.Rows[i][j]);
65                     }
66                 }
67 
68                 //自动列宽
69                 worksheet.AutoFitColumns();
70 
71                 //设置导出文件路径
72                 path = HttpContext.Current.Server.MapPath("Export/");
73 
74                 //设置新建文件路径及名称
75                 string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
76 
77                 //创建文件
78                 FileStream file = new FileStream(savePath, FileMode.CreateNew);
79 
80                 //关闭释放流,不然没办法写入数据
81                 file.Close();
82                 file.Dispose();
83 
84                 //保存至指定路径
85                 workbook.Save(savePath);
86 
87 
88                 //或者使用下面的方法,输出到浏览器下载。
89                 //byte[] bytes = workbook.SaveToStream().ToArray();
90                 //OutputClient(bytes);
91 
92                 worksheet = null;
93                 workbook = null;
94             }
95             catch(Exception ex)
96             {
97 
98             }
99         }
View Code
 1 public void OutputClient(byte[] bytes)
 2         {
 3             HttpContext.Current.Response.Buffer = true;
 4 
 5             HttpContext.Current.Response.Clear();
 6             HttpContext.Current.Response.ClearHeaders();
 7             HttpContext.Current.Response.ClearContent();
 8 
 9             HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
10             HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));
11 
12             HttpContext.Current.Response.Charset = "GB2312";
13             HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
14 
15             HttpContext.Current.Response.BinaryWrite(bytes);
16             HttpContext.Current.Response.Flush();
17 
18             HttpContext.Current.Response.Close();
19         }
View Code

第二种方法性能还不错,而且操作也不复杂,可以设置导出时文件保存的路径,还可以保存为流输出到浏览器下载。

第三种:Microsoft.Jet.OLEDB

这种方法操作 Excel 类似于操作数据库。下面先介绍一下连接字符串:

// Excel 2003 版本连接字符串
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/xxx.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=2;'";

// Excel 2007 以上版本连接字符串
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/xxx.xlsx;Extended Properties='Excel 12.0;HDR=Yes;IMEX=2;'";

Provider:驱动程序名称

Data Source:指定 Excel 文件的路径

Extended Properties:Excel 8.0 针对 Excel 2000 及以上版本;Excel 12.0 针对 Excel 2007 及以上版本。

HDR:Yes 表示第一行包含列名,在计算行数时就不包含第一行。NO 则完全相反。

IMEX:0 写入模式;1 读取模式;2 读写模式。如果报错为“不能修改表 sheet1 的设计。它在只读数据库中”,那就去掉这个,问题解决。

  1 public void ExportExcel(DataTable dt)
  2         {
  3             OleDbConnection conn = null;
  4             OleDbCommand cmd = null;
  5 
  6             Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
  7 
  8             Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.Workbooks;
  9 
 10             Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(true);
 11 
 12             try
 13             {
 14                 //设置区域为当前线程的区域
 15                 dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
 16 
 17                 //设置导出文件路径
 18                 string path = HttpContext.Current.Server.MapPath("Export/");
 19 
 20                 //设置新建文件路径及名称
 21                 string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
 22 
 23                 //创建文件
 24                 FileStream file = new FileStream(savePath, FileMode.CreateNew);
 25 
 26                 //关闭释放流,不然没办法写入数据
 27                 file.Close();
 28                 file.Dispose();
 29 
 30                 //由于使用流创建的 excel 文件不能被正常识别,所以只能使用这种方式另存为一下。
 31                 workbook.SaveCopyAs(savePath);
 32 
 33 
 34                 // Excel 2003 版本连接字符串
 35                 //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + savePath + "';Extended Properties='Excel 8.0;HDR=Yes;'";
 36 
 37                 // Excel 2007 以上版本连接字符串
 38                 string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"+ savePath + "';Extended Properties='Excel 12.0;HDR=Yes;'";
 39 
 40                 //创建连接对象
 41                 conn = new OleDbConnection(strConn);
 42                 //打开连接
 43                 conn.Open();
 44 
 45                 //创建命令对象
 46                 cmd = conn.CreateCommand();
 47 
 48                 //获取 excel 所有的数据表。
 49                 //new object[] { null, null, null, "Table" }指定返回的架构信息:参数介绍
 50                 //第一个参数指定目录
 51                 //第二个参数指定所有者
 52                 //第三个参数指定表名
 53                 //第四个参数指定表类型
 54                 DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
 55 
 56                 //因为后面创建的表都会在最后面,所以本想删除掉前面的表,结果发现做不到,只能清空数据。
 57                 for (int i = 0; i < dtSheetName.Rows.Count; i++)
 58                 {
 59                     cmd.CommandText = "drop table [" + dtSheetName.Rows[i]["TABLE_NAME"].ToString() + "]";
 60                     cmd.ExecuteNonQuery();
 61                 }
 62 
 63                 //添加一个表,即 Excel 中 sheet 表
 64                 cmd.CommandText = "create table " + dt.TableName + " ([S_Id] INT,[S_StuNo] VarChar,[S_Name] VarChar,[S_Sex] VarChar,[S_Height] VarChar,[S_BirthDate] VarChar,[C_S_Id] INT)";
 65                 cmd.ExecuteNonQuery();
 66 
 67                 for (int i = 0; i < dt.Rows.Count; i++)
 68                 {
 69                     string values = "";
 70 
 71                     for (int j = 0; j < dt.Columns.Count; j++)
 72                     {
 73                         values += "'" + dt.Rows[i][j].ToString() + "',";
 74                     }
 75 
 76                     //判断最后一个字符是否为逗号,如果是就截取掉
 77                     if (values.LastIndexOf(',') == values.Length - 1)
 78                     {
 79                         values = values.Substring(0, values.Length - 1);
 80                     }
 81 
 82                     //写入数据
 83                     cmd.CommandText = "insert into " + dt.TableName + " (S_Id,S_StuNo,S_Name,S_Sex,S_Height,S_BirthDate,C_S_Id) values (" + values + ")";
 84                     cmd.ExecuteNonQuery();
 85                 }
 86 
 87                 conn.Close();
 88                 conn.Dispose();
 89                 cmd.Dispose();
 90 
 91                 //加入下面的方法,把保存的 Excel 文件输出到浏览器下载。需要先关闭连接。
 92                 FileInfo fileInfo = new FileInfo(savePath);
 93                 OutputClient(fileInfo);
 94             }
 95             catch (Exception ex)
 96             {
 97 
 98             }
 99             finally
100             {
101                 workbook.Close(false, Type.Missing, Type.Missing);
102                 workbooks.Close();
103                 excel.Quit();
104 
105                 Marshal.ReleaseComObject(workbook);
106                 Marshal.ReleaseComObject(workbooks);
107                 Marshal.ReleaseComObject(excel);
108 
109                 workbook = null;
110                 workbooks = null;
111                 excel = null;
112 
113                 GC.Collect();
114             }
115         }
View Code
 1 public void OutputClient(FileInfo file)
 2         {
 3             HttpResponse response = HttpContext.Current.Response;
 4 
 5             response.Buffer = true;
 6 
 7             response.Clear();
 8             response.ClearHeaders();
 9             response.ClearContent();
10 
11             response.ContentType = "application/vnd.ms-excel";
12 
13             //导出到 .xlsx 格式不能用时,可以试试这个
14             //HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
15 
16             response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));
17 
18             response.Charset = "GB2312";
19             response.ContentEncoding = Encoding.GetEncoding("GB2312");
20 
21             response.AddHeader("Content-Length", file.Length.ToString());
22 
23             response.WriteFile(file.FullName);
24             response.Flush();
25 
26             response.Close();
27         }
View Code

这种方法需要指定一个已经存在的 Excel 文件作为写入数据的模板,不然的话就得使用流创建一个新的 Excel 文件,但是这样是没法识别的,那就需要用到 Microsoft.Office.Interop.Excel.dll 里面的 Microsoft.Office.Interop.Excel.Workbook.SaveCopyAs() 方法另存为一下,这样性能也就更差了。

使用操作命令创建的表都是在最后面的,前面的也没法删除(我是没有找到方法),当然也可以不再创建,直接写入数据也可以。

第四种:NPOI

NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前只支持 Office 97-2003 的文件格式。

NPOI 是免费开源的,操作也比较方便,下载地址:http://npoi.codeplex.com/

 1 public void ExportExcel(DataTable dt)
 2         {
 3             try
 4             {
 5                 //创建一个工作簿
 6                 IWorkbook workbook = new HSSFWorkbook();
 7 
 8                 //创建一个 sheet 表
 9                 ISheet sheet = workbook.CreateSheet(dt.TableName);
10 
11                 //创建一行
12                 IRow rowH = sheet.CreateRow(0);
13 
14                 //创建一个单元格
15                 ICell cell = null;
16 
17                 //创建单元格样式
18                 ICellStyle cellStyle = workbook.CreateCellStyle();
19 
20                 //创建格式
21                 IDataFormat dataFormat = workbook.CreateDataFormat();
22 
23                 //设置为文本格式,也可以为 text,即 dataFormat.GetFormat("text");
24                 cellStyle.DataFormat = dataFormat.GetFormat("@");
25 
26                 //设置列名
27                 foreach (DataColumn col in dt.Columns)
28                 {
29                     //创建单元格并设置单元格内容
30                     rowH.CreateCell(col.Ordinal).SetCellValue(col.Caption);
31 
32                     //设置单元格格式
33                     rowH.Cells[col.Ordinal].CellStyle = cellStyle;
34                 }
35 
36                 //写入数据
37                 for (int i = 0; i < dt.Rows.Count; i++)
38                 {
39                     //跳过第一行,第一行为列名
40                     IRow row = sheet.CreateRow(i + 1);
41 
42                     for (int j = 0; j < dt.Columns.Count; j++)
43                     {
44                         cell = row.CreateCell(j);
45                         cell.SetCellValue(dt.Rows[i][j].ToString());
46                         cell.CellStyle = cellStyle;
47                     }
48                 }
49 
50                 //设置导出文件路径
51                 string path = HttpContext.Current.Server.MapPath("Export/");
52 
53                 //设置新建文件路径及名称
54                 string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";
55 
56                 //创建文件
57                 FileStream file = new FileStream(savePath, FileMode.CreateNew,FileAccess.Write);
58 
59                 //创建一个 IO 流
60                 MemoryStream ms = new MemoryStream();
61 
62                 //写入到流
63                 workbook.Write(ms);
64 
65                 //转换为字节数组
66                 byte[] bytes = ms.ToArray();
67 
68                 file.Write(bytes, 0, bytes.Length);
69                 file.Flush();
70 
71                 //还可以调用下面的方法,把流输出到浏览器下载
72                 OutputClient(bytes);
73 
74                 //释放资源
75                 bytes = null;
76 
77                 ms.Close();
78                 ms.Dispose();
79 
80                 file.Close();
81                 file.Dispose();
82 
83                 workbook.Close();
84                 sheet = null;
85                 workbook = null;
86             }
87             catch(Exception ex)
88             {
89 
90             }
91         }
View Code
 1 public void OutputClient(byte[] bytes)
 2         {
 3             HttpResponse response = HttpContext.Current.Response;
 4 
 5             response.Buffer = true;
 6 
 7             response.Clear();
 8             response.ClearHeaders();
 9             response.ClearContent();
10 
11             response.ContentType = "application/vnd.ms-excel";
12             response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));
13 
14             response.Charset = "GB2312";
15             response.ContentEncoding = Encoding.GetEncoding("GB2312");
16 
17             response.BinaryWrite(bytes);
18             response.Flush();
19 
20             response.Close();
21         }
View Code

由于此方法目前只支持 office 2003 及以下版本,所以不能导出 .xlsx 格式的 Excel 文件。不过这种方法性能不错,而且操作方便。

第五种:GridView

直接使用 GridView 把 DataTable 的数据转换为字符串流,然后输出到浏览器下载。

 1 public void ExportExcel(DataTable dt)
 2         {
 3             HttpResponse response = HttpContext.Current.Response;
 4 
 5             response.Buffer = true;
 6 
 7             response.Clear();
 8             response.ClearHeaders();
 9             response.ClearContent();
10 
11             response.ContentType = "application/vnd.ms-excel";
12             response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));
13 
14             response.Charset = "GB2312";
15             response.ContentEncoding = Encoding.GetEncoding("GB2312");
16 
17             //实例化一个流
18             StringWriter stringWrite = new StringWriter();
19 
20             //指定文本输出到流
21             HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
22 
23             GridView gv = new GridView();
24             gv.DataSource = dt;
25             gv.DataBind();
26 
27             for (int i = 0; i < dt.Rows.Count; i++)
28             {
29                 for (int j = 0; j < dt.Columns.Count; j++)
30                 {
31                     //设置每个单元格的格式
32                     gv.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
33                 }
34             }
35 
36             //把 GridView 的内容输出到 HtmlTextWriter
37             gv.RenderControl(htmlWrite);
38             
39             response.Write(stringWrite.ToString());
40             response.Flush();
41 
42             response.Close();
43         }
View Code

这种方式导出 .xlsx 格式的 Excel 文件时,没办法打开。导出 .xls 格式的,会提示文件格式和扩展名不匹配,但是可以打开的。

第六种:DataGrid

其实这一种方法和上面的那一种方法几乎是一样的。

 1 public void ExportExcel(DataTable dt)
 2         {
 3             HttpResponse response = HttpContext.Current.Response;
 4 
 5             response.Buffer = true;
 6 
 7             response.Clear();
 8             response.ClearHeaders();
 9             response.ClearContent();
10 
11             response.ContentType = "application/vnd.ms-excel";
12             response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));
13 
14             response.Charset = "GB2312";
15             response.ContentEncoding = Encoding.GetEncoding("GB2312");
16 
17             //实例化一个流
18             StringWriter stringWrite = new StringWriter();
19 
20             //指定文本输出到流
21             HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
22 
23             DataGrid dg = new DataGrid();
24             dg.DataSource = dt;
25             dg.DataBind();
26 
27             dg.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
28 
29             //把 DataGrid 的内容输出到 HtmlTextWriter
30             dg.RenderControl(htmlWrite);
31 
32             response.Write(stringWrite.ToString());
33             response.Flush();
34 
35             response.Close();
36         }
View Code

第七种:直接使用 IO 流

第一种方式,使用文件流在磁盘创建一个 Excel 文件,然后使用流写入数据。

 1 public void ExportExcel(DataTable dt)
 2         {
 3             //设置导出文件路径
 4             string path = HttpContext.Current.Server.MapPath("Export/");
 5 
 6             //设置新建文件路径及名称
 7             string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";
 8 
 9             //创建文件
10             FileStream file = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write);
11             
12             //以指定的字符编码向指定的流写入字符
13             StreamWriter sw = new StreamWriter(file, Encoding.GetEncoding("GB2312"));
14 
15             StringBuilder strbu = new StringBuilder();
16 
17             //写入标题
18             for (int i = 0; i < dt.Columns.Count; i++)
19             {
20                 strbu.Append(dt.Columns[i].ColumnName.ToString() + "	");
21             }
22             //加入换行字符串
23             strbu.Append(Environment.NewLine);
24 
25             //写入内容
26             for (int i = 0; i < dt.Rows.Count; i++)
27             {
28                 for (int j = 0; j < dt.Columns.Count; j++)
29                 {
30                     strbu.Append(dt.Rows[i][j].ToString() + "	");
31                 }
32                 strbu.Append(Environment.NewLine);
33             }
34 
35             sw.Write(strbu.ToString());
36             sw.Flush();
37             file.Flush();
38             
39             sw.Close();
40             sw.Dispose();
41 
42             file.Close();
43             file.Dispose();
44         }
View Code

第二种方式,这种方式就不需要在本地磁盘创建文件了,首先创建一个内存流写入数据,然后输出到浏览器下载。

 1 public void ExportExcel(DataTable dt)
 2         {
 3             //创建一个内存流
 4             MemoryStream ms = new MemoryStream();
 5 
 6             //以指定的字符编码向指定的流写入字符
 7             StreamWriter sw = new StreamWriter(ms, Encoding.GetEncoding("GB2312"));
 8 
 9             StringBuilder strbu = new StringBuilder();
10 
11             //写入标题
12             for (int i = 0; i < dt.Columns.Count; i++)
13             {
14                 strbu.Append(dt.Columns[i].ColumnName.ToString() + "	");
15             }
16             //加入换行字符串
17             strbu.Append(Environment.NewLine);
18 
19             //写入内容
20             for (int i = 0; i < dt.Rows.Count; i++)
21             {
22                 for (int j = 0; j < dt.Columns.Count; j++)
23                 {
24                     strbu.Append(dt.Rows[i][j].ToString() + "	");
25                 }
26                 strbu.Append(Environment.NewLine);
27             }
28 
29             sw.Write(strbu.ToString());
30             sw.Flush();
31 
32             sw.Close();
33             sw.Dispose();
34 
35             //转换为字节数组
36             byte[] bytes = ms.ToArray();
37 
38             ms.Close();
39             ms.Dispose();
40 
41             OutputClient(bytes);
42         }
View Code
 1 public void OutputClient(byte[] bytes)
 2         {
 3             HttpResponse response = HttpContext.Current.Response;
 4 
 5             response.Buffer = true;
 6 
 7             response.Clear();
 8             response.ClearHeaders();
 9             response.ClearContent();
10 
11             response.ContentType = "application/vnd.ms-excel";
12             response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));
13 
14             response.Charset = "GB2312";
15             response.ContentEncoding = Encoding.GetEncoding("GB2312");
16 
17             response.BinaryWrite(bytes);
18             response.Flush();
19 
20             response.Close();
21         }
View Code

这种方法有一个弊端,就是不能设置单元格的格式(至少我是没有找到,是在下输了)。

[转载http://www.cnblogs.com/Brambling/p/6854731.html]

原文地址:https://www.cnblogs.com/wangpd/p/6866492.html