最近在做asp.net项目,在此过程中用到Excel导出,我整理了导出数据源到Excel模版文件的共同方法,分享给大家!
如果大家还有更好的方法,可以分享给我,谢谢!
方法一:利用Microsoft.Office.Interop.Excel
首先要引用using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
/// 导出数据到Excel模板文件
/// </summary>
/// <param name="DT">数据源</param>
/// <param name="templateFile">模板文件</param>
/// <param name="tempFile">临时文件</param>
/// <param name="Response">客户端响应</param>
/// <param name="fileName">文件名称</param>
public static bool ExportExcel(DataTable DT, string templateFile, string tempFile, HttpResponse Response,string fileName)
{
try
{
Excel.Application myExcel = new Excel.Application();
//不单独显示Excel,最后在IE中显示
myExcel.Visible = false;
//指定模板文件
FileInfo mode = new FileInfo(templateFile);
//打开复制后的文件X
object missing = Missing.Value;
//打开模板文件
myExcel.Application.Workbooks.Open
(mode.FullName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
Excel.Workbook myBook = myExcel.Workbooks[1];
Excel.Worksheet mySheet = myBook.Worksheets[1] as Excel.Worksheet;
Excel.Range range1 = mySheet.Rows[2, missing] as Excel.Range;
//复制行(在指定行下面复制指定数量行)
for (int j = 1; j <= DT.Rows.Count - 1; j++)
{
Excel.Range range2 = mySheet.Rows[2 + j, missing] as Excel.Range;
range1.Copy(range2);
}
//设置Sheet名
mySheet.Name = fileName;
//将dt中的数据写入WorkSheet
for (int i = 0; i < DT.Rows.Count; i++)
{
for (int k = 0; k < DT.Columns.Count; k++)
{
mySheet.Cells[i + 2, k + 1] = DT.Rows[i][k].ToString();
}
}
//在当前目录下指定一个临时文件,如果临时文件已经存在则删除临时文件
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
//保存文件
myBook.SaveAs(tempFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing);
mySheet.Cells.Clear();
//设置不出现保存提示框
myBook.Saved = true;
myExcel.Application.Workbooks.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/ms-excel";
//文件名
string ExcelName = fileName+"_[" + DateTime.Now.ToString("yyyyMMddhhmmss")+"]";
Response.AddHeader("Content-Disposition", "attachment; filename=" +
System.Web.HttpUtility.UrlEncode(ExcelName, System.Text.Encoding.UTF8) + ".xls");
Response.WriteFile(tempFile);
Response.Flush();
Response.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
获取模板文件和创建临时文件的方法:
string templateFile = Server.MapPath("~/Excel_Template/orderList_template.xls");
string tempFile = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString() + ".xls");
方法二:利用OleDb驱动程序写入Excel模板文件
/// <summary>
/// 导出Excel模板
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="fileName">模板文件</param>
/// <param name="tempFileName">模板文件的副本</param>
/// <param name="saveExcelName">要保存的Excel文件的名字</param>
/// <param name="Response">客户端响应</param>
/// <returns>true or false</returns>
public static bool ExportDataToExcel(DataTable dt, string templateFile, string tempFile, string saveExcelName, string[] coloumns, string[] values, HttpResponse Response)
{
try
{
//设置目标模板文件为正常状态
if (File.Exists(templateFile))
File.SetAttributes(templateFile, FileAttributes.Normal);
// 根据模板文件创建副本
File.Copy(templateFile, tempFile);
// 使用OleDb驱动程序连接到副本
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + tempFile + ";Extended Properties=Excel 8.0;");
using (conn)
{
conn.Open(); //打开连接
for (int i = 0; i < dt.Rows.Count; i++)
{
StringBuilder sb = new StringBuilder("INSERT INTO [Sheet1$](");
//添加Excel插入语句列
for (int j = 0; j < coloumns.Length; j++)
{
if (j == coloumns.Length - 1)
{
sb.Append("[" + coloumns[j] + "]");
}
else
{
sb.Append("[" + coloumns[j] + "]" + ",");
}
}
sb.Append(") VALUES(");
//添加Excel插入语句参数
for (int k = 0; k < values.Length; k++)
{
if (k == values.Length - 1)
{
sb.Append("@" + values[k]);
}
else
{
sb.Append("@" + values[k] + ",");
}
}
sb.Append(")");
// 增加记录
OleDbCommand cmd = new OleDbCommand(sb.ToString(), conn);
//给Excel插入语句参数赋值
for (int z = 0; z < coloumns.Length; z++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][z].ToString()))
{
cmd.Parameters.AddWithValue(values[z], dt.Rows[i][z]);
}
else
{
cmd.Parameters.AddWithValue(values[z], " ");
}
}
int result = cmd.ExecuteNonQuery();
}
conn.Close(); //关闭连接
}
// 输出副本的二进制字节流
Response.ContentType = "application/ms-excel";
//文件名
string ExcelName = saveExcelName + DateTime.Now.ToString("yyyyMMddhhmmss");
Response.AddHeader("Content-Disposition", "attachment; filename=" +
System.Web.HttpUtility.UrlEncode(ExcelName, System.Text.Encoding.UTF8) + ".xls");
Response.BinaryWrite(File.ReadAllBytes(tempFile));
// 删除副本
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
catch (Exception ex)
{
return false;
}
return true;
}
//调用共同方法导出数据到Excel模版文件
/// <summary>
/// 导出数据到Excel模板
/// </summary>
private void ExportInventoryExcel()
{
string templateFile = Server.MapPath("~/Excel_Template/inventory_template.xls");
string tempFile = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString() + ".xls");
//获取数据源
DataTable dt = this.cteateTable();
//Excel插入语句列名
string[] columns = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
columns[i] = dt.Columns[i].ColumnName;
}
//Excel插入语句参数名
//注意:该参数数量一定要与模板文件的列数一致,有多少列就要设置多少个参数
string[] values = { "ProductNo", "ProductName", "GoodsNo", "FacoryProductNo", "Amount", "SKUColour", "SKUSize", "SKUMaterial", "SKUEtc", "ProductType",
"SupplierCd", "Lot", "EnteringDate", "Memo"};
bool result = CommonMethod.ExportDataToExcel(dt, templateFile, tempFile, Constant.INVENTORY, columns, values, Response);
// 删除副本
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
if (!result)
{
ClientScript.RegisterStartupScript(Page.GetType(), "",
" <Script>导出文件失败</Script>");
}
}
注意:DataTable里的列要与Excel模版文件的列一致,Excel模版文件单元格的格式最好都设置为文本格式,以免出问题。