首页 新闻 搜索 专区 学院

Easyui datagrid表格中数据导入excel

0
悬赏园豆:20 [待解决问题]

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中了,但是里面有好多错,现在不知道怎么解决了,求哪一位大神指导下我,谢谢!

 

zero219的主页 zero219 | 初学一级 | 园豆:182
提问于:2018-01-02 23:41
< >
分享
所有回答(2)
0

错误截图你要贴出来,要不然怎么帮你解决呢

隔壁老黎 | 园豆:101 (初学一级) | 2018-01-03 10:10


这个是HSSFWorkbook workbook = new HSSFWorkbook();报错的

这个是ICell cell = rows.CreateCell(i);报错ICell cell = rows.CreateCell(j);报错MemoryStream ms = new MemoryStream();报错

支持(0) 反对(0) zero219 | 园豆:182 (初学一级) | 2018-01-03 11:26

@很帅很低调: 写法上没看出有什么问题,你还是检查一下你使用的NPOI版本,看是否和你模拟的你篇版本相同;后续出现的异常应该是你前面异常引发的连锁反应;

支持(0) 反对(0) 隔壁老黎 | 园豆:101 (初学一级) | 2018-01-03 11:57

@隔壁老黎: //return File(ms, "application/vnd.ms-excel", fileName);是mvc里的写法,context.Response.Write(ms);是我改的。这里是不是有问题?

支持(0) 反对(0) zero219 | 园豆:182 (初学一级) | 2018-01-03 16:39
0

用Free Spire.XLS导入Excel吧,简单

http://blog.csdn.net/eiceblue/article/details/78563323

ms_doudou | 园豆:624 (小虾三级) | 2018-01-03 11:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册