用了好多种方案,最后发现NPOI是最好使的,下面这段代码是从我的项目中扣下来了,给你提供个思路
HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.CreateSheet(string.Format("{0}.{1}.{2} - {3}.{4}.{5}", startDate.Year, startDate.Month, startDate.Day, endDate.Year, endDate.Month, endDate.Day));
var style1 = workbook.CreateCellStyle();
style1.BorderBottom = style1.BorderLeft = style1.BorderRight = style1.BorderTop = CellBorderType.THIN;
style1.BottomBorderColor = style1.RightBorderColor = style1.LeftBorderColor = style1.TopBorderColor = HSSFColor.BLACK.index;
var style2 = workbook.CreateCellStyle();
style2.BorderBottom = style2.BorderLeft = style2.BorderRight = style2.BorderTop = CellBorderType.THIN;
style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_25_PERCENT.index;
style2.FillPattern = FillPatternType.SOLID_FOREGROUND;
for (int i = 0; i <= reportData.Count; i++)
{
var row = sheet.CreateRow(i);
for (int j = 0; j < 29; j++)
{
Cell cell = row.CreateCell(j);
cell.CellStyle = style1;
switch (j)
{
case 0:
{
cell.SetCellValue(reportData[i - 1].DeptName);
break;
}
case 1:
{
cell.CellStyle = style2;
cell.SetCellValue(reportData[i - 1].DeptEmpNumber);
break;
}
case 2:
{
cell.SetCellValue(reportData[i - 1].IDLN);
break;
}
}
}
}
if (context == null)
throw new ApplicationException("Current System.Web.HttpContext not found - Send failed.");
if (!context.Response.Buffer)
{
context.Response.Buffer = true;
context.Response.Clear();
}
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", string.Format("{0};filename={1}_{2}_{3}.xls", "attachment", "MonthlyReport", startDate.ToShortDateString(), endDate.ToShortDateString()));
context.Response.Flush();
context.Response.BinaryWrite(ms.ToArray());
workbook = null;
ms.Close();
ms.Dispose();