日期:2014-05-18 浏览次数:20946 次
private void GenerateReport()
{
//Create Excel Application
Excel._Application excelApp = new Excel.Application();
Excel._Workbook excelFile;
Excel._Worksheet sheetTrustee, sheetInsurer, sheetIssuer, sheetAcctDetail;
//Get 3 spread sheets
excelFile = excelApp.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true);
sheetTrustee = (Excel._Worksheet)excelFile.Worksheets.get_Item(1);
int i=0;
List<MyModelClass> list = GetMyDataSource(); //获得你的Model List
foreach(MyModelClass item in list)
{
//Insert new row in template
((Excel.Range)sheetTrustee.Cells[3+idx, 1]).EntireRow.Insert(Missing.Value);
//Set values in new row
sheetTrustee.Cells[i, 0] = item.UserName;
sheetTrustee.Cells[i, 1] = item.XXX;
sheetTrustee.Cells[i, 2] = item.????;
}
//Save & Close
excelApp.DisplayAlerts = false;
excelFile.Close(true, @"C:\filenamexxx", Missing.Value);
excelApp.Quit();
}
------解决方案--------------------
//输出到客户端
Response.AddHeader("Content-Disposition", "attachment; filename=Employee.xls" );
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write( this.mString.ToString() ); // 把文件流发送到客户端
Response.End();
其中 mString为经过格式化的字符串,excel的字符格式如
内容\t内容\t\r\n
内容\t内容\t\r\n