NPOI还是比较好用的,引用dll程序集即可
1创建workbook和工作流
HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream();
2这里是一个多sheet的例子,可以通过循环一个个生成
1 List<DataTable> listtable = new List<DataTable>(); 2 for(int t = 1; t < = listtable.Count();t++) 3 { 4 DataTable tempTable = listtable[t-1]; 5 //增加sheet,listname是一个List<string>作为表明 6 HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(listname[t-1]); 7 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); 8 foreach(DataColumn column in tempTable.Columns) 9 { 10 //创建列 11 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 12 } 13 int rowIndex = 1; 14 foreach(DataRow row in tempTable.Rows) 15 { 16 //创建行 17 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); 18 foreach(DataColumn column in tempTable.Columns) 19 { 20 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); 21 } 22 rowIndex++; 23 } 24 }
3工作中的sheet都创建好之后,写入流
workbook.Write(ms);
4最后返回给浏览器端
byte[] strmByte = ms.ToArray(); ms.Dispose(); Response.ClearContent(); Response.ContentEncoding = System.Text.Encoding.UTF8; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition","attachment;fileName="+"name.xlsx"); Response.BinaryWrite(strmByte);