public void ProcessRequest(HttpContext context)
{
DataTable dt = new DataTable();
dt = Service.Excel();
string strFileName = "Excel";
//创建excel文件流
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = string.IsNullOrEmpty(strFileName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(strFileName);
//表头
IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
//创建列的样式
HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
//居中显示
cellStyle.Alignment = HorizontalAlignment.Center;
//垂直居中
cellStyle.VerticalAlignment = VerticalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 12;
font.FontName = "宋体";
font.IsBold = true;
cellStyle.SetFont(font);
cell.CellStyle = cellStyle;
}
//数据
int[] len = new int[dt.Columns.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
//行
IRow rows = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
//列
ICell cell = rows.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
var lenTemp = dt.Rows[i][j].ToString().Length > dt.Columns[j].ColumnName.Length ? dt.Rows[i][j].ToString().Length : dt.Columns[j].ColumnName.Length;
if (lenTemp > len[j])
{
len[j] = lenTemp;
}
}
}
//自动设置列宽
for (int i = 0; i < len.Length; i++)
{
if (len[i] < 8)
{
len[i] = Convert.ToInt32(Math.Round(len[i] * 2.5));
}
else
{
len[i] = Convert.ToInt32(Math.Round(len[i] * 1.3));
}
sheet.SetColumnWidth(i, len[i] * 256);
}
//写入到客户端
MemoryStream ms = new MemoryStream(); //创建其支持存储区为内存的流
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
string fileName = strFileName + DateTime.Now.ToString("yyMMddHHmmssfff") + ".xls";
context.Response.Write(ms);
//return File(ms, "application/vnd.ms-excel", fileName);
}
这是别人在mvc中写的,我模仿它的写法把它放在.net中了,但是里面有好多错,现在不知道怎么解决了,求哪一位大神指导下我,谢谢!
错误截图你要贴出来,要不然怎么帮你解决呢
这个是HSSFWorkbook workbook = new HSSFWorkbook();报错的
这个是ICell cell = rows.CreateCell(i);报错ICell cell = rows.CreateCell(j);报错MemoryStream ms = new MemoryStream();报错
@很帅很低调: 写法上没看出有什么问题,你还是检查一下你使用的NPOI版本,看是否和你模拟的你篇版本相同;后续出现的异常应该是你前面异常引发的连锁反应;
@隔壁老黎: //return File(ms, "application/vnd.ms-excel", fileName);是mvc里的写法,context.Response.Write(ms);是我改的。这里是不是有问题?