Npoi 生成excel报表功能很不错,功能也不用给大家介绍了。首先看遇到的问题吧!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
FileStream file = new
FileStream(Server.MapPath( "Templatetest.xls" ), FileMode.Open, FileAccess.Read);
HSSFWorkbook existWorkbook = new
HSSFWorkbook(file);
HSSFSheet sheet1 = (HSSFSheet)existWorkbook.GetSheet( "Sheet1" );
sheet1.GetRow(1).GetCell(1).SetCellValue( "新闻" );
sheet1.GetRow(2).GetCell(1).SetCellValue( "娱乐" );
sheet1.GetRow(3).GetCell(1).SetCellValue( "Angel工作室" );
//Force excel to recalculate all the formula while open
sheet1.ForceFormulaRecalculation = true ;
//输出报表
HssfworkbookToaDownloadFile( @"测试表名称.xls" , hssfworkbooks);
/// <summary> /// hssfworkbook输出为下载文件 /// </summary> /// <param name="filename"></param> private
void HssfworkbookToaDownloadFile( string
filename, HSSFWorkbook hssfworkbook)
{ if
(HttpContext.Current.Request.UserAgent.ToLower().IndexOf( "msie" ) > -1)
{
filename = HttpContext.Current.Server.UrlPathEncode(filename);
}
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" ;
HttpContext.Current.Response.AddHeader( "Content-Disposition" , string .Format( "attachment;filename={0}" , filename));
HttpContext.Current.Response.Clear();
MemoryStream file = new
MemoryStream();
hssfworkbook.Write(file);
HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
HttpContext.Current.Response.End();
} |
以上代码显然是看不出哪里有问题,但是就是报空的异常。
1
|
sheet1.GetRow(1).GetCell(1).SetCellValue( "新闻" );<br>这样第一行就错误报 null 异常。最后发现模板的问题,因为新建的模板没有什么值所以必须创建一下就搞定了。<br>代码如下修改:
|
1
2
3
4
5
6
7
8
|
if (sheet1.GetRow(1) == null )
{ sheet1.CreateRow(1);
} if (sheet1.GetRow(1).GetCell(1) == null )
{ sheet1.GetRow(1).CreateCell(1);
} |
希望能帮到大家,有什么技术问题大家可以讨论。