using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
namespace Common
{
public class ExcelHelper
{
public static string Pbint;
/// <summary>
/// 将DataTable中的数据导出到excel中
/// </summary>
/// <param name="dsT"></param>
/// <param name="saveFileName">存储路径</param>
/// <param name="bookname">表格头 可以为空串</param>
/// <returns></returns>
public static string ExportExcel(DataTable dsT, string saveFileName, string bookname)
{
DataSet ds1 = new DataSet();
try
{
ds1.Tables.Add(dsT); //datatable转为dataset
// gridbind();
if (ds1 == null) return "表格为空";
Excel.Application xlApp = new Excel.Application();
object missing = System.Reflection.Missing.Value;
if (xlApp == null)
{
return ("无法创建Excel对象,可能您的计算机可能没有安装Excel");
}
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range;
long totalCount = ds1.Tables[0].Rows.Count;
long rowRead = 0;
float percent = 0;
//写入字段
if (bookname == "")
{
//写入标题
for (int i = 0; i < ds1.Tables[0].Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = ds1.Tables[0].Columns[i].ColumnName;
range = (Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 20;
range.Font.Bold = true;
}
//写入数值
for (int r = 0; r < ds1.Tables[0].Rows.Count; r++)
{
for (int i = 0; i < ds1.Tables[0].Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = ds1.Tables[0].Rows[r][i];
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
Pbint = "正在导出数据[" + percent.ToString("0.00") + "%]...";
}
range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[ds1.Tables[0].Rows.Count + 1, ds1.Tables[0].Columns.Count]];
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
if (ds1.Tables[0].Columns.Count > 1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
}
}
else
{
worksheet.Name = bookname;
worksheet.Cells[1, 1] = bookname;
range = (Excel.Range)worksheet.Cells[1, 1];
// range.Interior.ColorIndex = 10;
range.Font.Bold = true;
range.Font.Size = 12;
range.RowHeight = 22; //行高
// range.Columns .AutoFilter(); //自动列宽
for (int i = 0; i < ds1.Tables[0].Columns.Count; i++)
{
worksheet.Cells[2, i + 1] = ds1.Tables[0].Columns[i].ColumnName;
range = (Excel.Range)worksheet.Cells[2, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//写入数值
// Caption.Visible = true;
for (int r = 0; r < ds1.Tables[0].Rows.Count; r++)
{
for (int i = 0; i < ds1.Tables[0].Columns.Count; i++)
{
worksheet.Cells[r + 3, i + 1] = ds1.Tables[0].Rows[r][i];
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
Pbint = "正在导出数据[" + percent.ToString("0.00") + "%]...";
range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[ds1.Tables[0].Rows.Count + 2, ds1.Tables[0].Columns.Count]];
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
if (ds1.Tables[0].Columns.Count > 1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
}
}
}
workbook.SaveAs(saveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(missing, missing, missing);
xlApp.Quit();
}
catch(Exception ex)
{
return ex.Message;//“object”未包含“get_Range”的定义
}
return "导出完成!";
}
}
}
注意该方式可能会由于Office的版本问题,出现方法签名不一致的错误。
下面介绍通过NPOI方式下载文件的方式,该方式的优点是不需要服务器端安装Office软件。实现的思路是,首先用户请求ashx一般处理程序,一般处理程序会查询数据库,然后将数据库中的相关信息保存在DataTable中,再通过NPOI提供的接口方法,将DataTable中的数据保存到本地,生成一个Excel文件,最终ashx一般处理程序会生成一个URL链接,即为文件在服务器上的地址,前台ajax请求的success处理函数中将请求重定向到该URL链接,即可实现文件的下载。(注意需要下载NPOI.dll)
/// <summary>
/// 实体类集合导出到EXCLE2003
/// </summary>
/// <param name="enList">数据源</param>
/// <param name="sheetName">工作表名称</param>
/// <returns>文件的下载地址</returns>
public static string EntityListToExcel2003(DataTable dTable)
{
try
{
string fileName = dTable.TableName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; // 文件名称
string urlPath = "/Files/Excels/" + fileName; // 文件下载的URL地址,供给前台下载
string filePath = HttpContext.Current.Server.MapPath("\\" + urlPath); // 文件路径
// 1.检测是否存在文件夹,若不存在就建立个文件夹
string directoryName = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
// 2.解析单元格头部
HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿
ISheet sheet = workbook.CreateSheet(dTable.TableName); // 工作表
IRow row = sheet.CreateRow(0);
// 设置列名称
for (int i = 0; i < dTable.Columns.Count; i++)
{
row.CreateCell(i).SetCellValue(dTable.Columns[i].ColumnName);
}
// 3.List对象的值赋值到Excel的单元格里
for (int i = 1; i <= dTable.Rows.Count; i++)
{
IRow rowTmp = sheet.CreateRow(i);
for (int j = 0; j < dTable.Columns.Count; j++) // 根据指定的属性名称,获取对象指定属性的值
{
string cellValue = dTable.Rows[i - 1][j].ToString(); // 单元格的值
rowTmp.CreateCell(j).SetCellValue(cellValue);
}
}
// 4.生成文件
FileStream file = new FileStream(filePath, FileMode.Create);
workbook.Write(file);
file.Close();
// 5.返回下载路径
return urlPath;
}
catch (Exception ex)
{
throw ex;
}
}
//数据导出
function toExcel() {
$.ajax({
url: '/JZ/JZHandler.ashx?action=ToExcel',
type: 'POST',
data: {
JZId: $('#tt').tree('getRoot').text,
Start: $('#dd1').datebox('getValue'),
End: $('#dd2').datebox('getValue')
},
beforeSend: function () {
$.messager.progress({
text: '正在处理中...'
})
},
success: function (data) {
$.messager.progress('close');
data = eval('(' + data + ')'); //通过重定向到文件的地址即可实现文件的下载
location.href = data;
}
});
}