参考网址1:http://www.it165.net/pro/html/201405/13609.html
参考网址2:http://blog.csdn.net/halym/article/details/9235823
//360内核使用【将datatable转为excel并且下载】
public void DataTableToExcelDownload(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(SimpleChinaeseName(data.Columns[j].ColumnName));
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
HttpContext.Current.Response.Clear();
workbook.Write(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)));
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}