Excel操作之 导出生成多个sheet页面
首先需要下载一个NPOI.dll
下载地址:http://download.csdn.net/detail/president810/9503038
using System; using System.Collections.Generic; using System.IO;
//引用NPOI using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; namespace Sola.ExportTakeClass { public class ExportToExcelUtil { private string _excelPath = ""; private IWorkbook workbook; private ISheet sheet; private int row = 0; private IList<string> sheetList = new List<string>(); public ExportToExcelUtil(string excelPath,IList<string> sheetList) { _excelPath = excelPath; this.sheetList = sheetList; ExcelFormat(); } /// <summary> /// 遍历sheet 并添加到excel /// </summary> private void ExcelFormat() { try { workbook = new HSSFWorkbook(); foreach (var sheetname in sheetList) { workbook.CreateSheet(sheetname); } } catch { GC.Collect(); GC.Collect(1); } } /// <summary> /// 将头部列表添加至 指定的sheet页 /// </summary> /// <param name="titleList"></param> /// <param name="sheetName"></param> public void SetHead(IList<string> titleList,string sheetName) { row = 0; sheet = workbook.GetSheet(sheetName); IRow headerRow = sheet.CreateRow(row); int col = 0; foreach (string t in titleList) { headerRow.CreateCell(col).SetCellValue(t); col++; } } /// <summary> /// 将数据写入指定的 sheet页 /// </summary> /// <param name="valueList"></param> /// <param name="sheetName"></param> public void WriteExcel(IList<string> valueList, string sheetName) { int col = 0; sheet = workbook.GetSheet(sheetName); row++; IRow itemRow = sheet.CreateRow(row); foreach (string v in valueList) { itemRow.CreateCell(col).SetCellValue(v); col++; } } public void Close() { try { FileStream file = new FileStream(_excelPath, FileMode.Create); workbook.Write(file); file.Close(); workbook.Clear(); } finally { GC.Collect(); GC.Collect(1); } } } }