C#将DataTable数据导出到EXCEL的两种方法
Posted John_杰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#将DataTable数据导出到EXCEL的两种方法相关的知识,希望对你有一定的参考价值。
1、在非服务器控件的页面导出数据,需要借助一张temp空页面post回后台的数据。
前台:window.location.href = "../Temp.aspx";
后台: try{
dtSource = Session["MyDataTable"] //假设数据在Session中
if (dtSource == null || dtSource.Rows.Count == 0)
{
return;
}
DataGrid dg = new DataGrid();
dg.DataSource = dtSource;
dg.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";//GB2312
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";//text/csv
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
System.IO.StringWriter oSW = new System.IO.StringWriter();
htmlTextWriter oHW = new HtmlTextWriter(oSW);
dg.RenderControl(oHW);
HttpContext.Current.Response.Write(oSW.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}catch(e){
log.Error(e);
Response.Redirect("原页面.aspx");
}
2、通过引用 Microsoft.Office.Interop.Excel.dll 和 Microsoft.CSharp.dll,不推荐,服务器需要安装Office才行
/// <summary>
/// 该方法需要引用Microsoft.Office.Interop.Excel.dll 和 Microsoft.CSharp.dll
/// 将数据由DataTable导出到Excel
/// </summary>
/// <param name="dataTable"></param>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
private string exportDataTableToExcel(DataTable dataTable, string fileName, string filePath)
{
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel._Workbook workBook;
Microsoft.Office.Interop.Excel._Worksheet workSheet;
object misValue = System.Reflection.Missing.Value;
excel = new Microsoft.Office.Interop.Excel.Application();
workBook = excel.Workbooks.Add(misValue);
workSheet = (Microsoft.Office.Interop.Excel._Worksheet)workBook.ActiveSheet;
int rowIndex = 1;
int colIndex = 0;
//取得标题
foreach (DataColumn col in dataTable.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
//取得表格中的数据
foreach (DataRow row in dataTable.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in dataTable.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] =
row[col.ColumnName].ToString().Trim();
//设置表格内容居中对齐
//workSheet.get_Range(excel.Cells[rowIndex, colIndex],
// excel.Cells[rowIndex, colIndex]).HorizontalAlignment =
// Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
}
}
excel.Visible = true;
string saveFile = filePath + fileName + ".xls";
if (File.Exists(saveFile))
{
File.Delete(saveFile);//嘿嘿,这样不好,偷偷把原来的删掉了,暂时这样写,项目中不可以
}
workBook.SaveAs(saveFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue,
misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
dataTable = null;
workBook.Close(true, misValue, misValue);
excel.Quit();
PublicMethod.Kill(excel);//调用kill当前excel进程
releaseObject(workSheet);
releaseObject(workBook);
releaseObject(excel);
if (!File.Exists(saveFile))
{
return null;
}
return saveFile;
}
/// <summary>
/// 释放COM组件对象
/// </summary>
/// <param name="obj"></param>
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch
{
obj = null;
}
finally
{
GC.Collect();
}
}
/// <summary>
/// 关闭进程的内部类
/// </summary>
public class PublicMethod
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
{
//如果外层没有try catch方法这个地方需要抛异常。
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}
}
以上是关于C#将DataTable数据导出到EXCEL的两种方法的主要内容,如果未能解决你的问题,请参考以下文章