DataTable To Excel
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
public partial class Excel : System.Web.UI.Page
{
SQLHelper sqlH;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnExport_Click(object sender, EventArgs e)
{
string str = "SELECT [classID],[className] FROM [SchoolNews].[dbo].[newsClass] ";
string excelName = "KQ";
string createTime = DateTime.Now.ToString("yyyyMMdd");
Export(str,excelName);
}
protected void Export(string str,string excelName)
{
// sqlH = new SQLHelper();
//string str = "SELECT [classID],[className] FROM [SchoolNews].[dbo].[newsClass] ";
SqlConnection sqlCon = new SqlConnection("server=.;database=schoolnews;uid=sa;pwd=;");
sqlCon.Open();
SqlCommand sqlcom = new SqlCommand(str, sqlCon);
System.Data.SqlClient.SqlDataReader sdr = sqlcom.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(sdr);
sdr.Close();
sqlCon.Close();
int[] index = { 0, 1 };
string[] heads = { "classID", "className" };
//string name = Server.MapPath("file/template.xls");
string name = "C:\\excel\\"+excelName+".xlsx";
ExportToExcel(dt, "C:\\excel\\" + excelName + ".xlsx", index, heads);// Server.MapPath("file/template.xls")
System.IO.FileInfo aFile = new System.IO.FileInfo(name);
string na = Path.GetFileName(name);
Response.Clear();
Response.ClearHeaders();
Response.BufferOutput = false;
Response.ContentType = "application/ms-excel";
//Response.AddHeader("Content-Disposition","attachment;filename="+na);
//上面这条中文会乱码,应该下面这样写
Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(na, System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", aFile.Length.ToString());
Response.WriteFile(name);
Response.Flush();
Response.End();
}
public static bool ExportToExcel(System.Data.DataTable table, string excelName, int[] columnIndexs, string[] columnHeads)
{
#region 将方法中用到的所有Excel变量声明在方法最开始,以便最后统一回收。
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass oExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook obook = null;
Microsoft.Office.Interop.Excel.Worksheet oSheet = null;
Microsoft.Office.Interop.Excel.Range range = null;
#endregion
try
{
obook = oExcel.Workbooks.Add("");
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets[1];
int rCount, cCount;
rCount = table.Rows.Count;
cCount = table.Columns.Count;
object obj = System.Reflection.Missing.Value;
if (cCount < columnIndexs.Length || cCount < columnHeads.Length)
{
throw new ArgumentOutOfRangeException("columnIndexs 与 columnHeads 长度必须一致。");
}
for (int i = 1; i <= columnIndexs.Length; i++)
{
//Excel.Range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
range = (Microsoft.Office.Interop.Excel.Range)oSheet.Columns.get_Item(i, obj);
range.NumberFormatLocal = "@";
}
for (int c = 0; c < columnIndexs.Length; c++)
{
oSheet.Cells[1, c + 1] = columnHeads[c];
for (int r = 1; r <= rCount; r++)
{
oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString();
}
}
obook.Saved = true;
obook.SaveCopyAs(excelName);
//必须调用 obook.Close(), 否则无法释放进程。
obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
// 调用System.Runtime.InteropServices.Marshal.ReleaseComObject(object)方法释放方法中
//用到的所有的Excel 变量, 记住是所有的。 比如说此方法中的range 对象, 就容易被遗忘。
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(obook);
// 很多文章上都说必须调用此方法, 但是我试过没有调用oExcel.Quit() 的情况, 进程也能安全退出,
//还是保留着吧。
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
// 垃圾回收是必须的。 测试如果不执行垃圾回收, 无法关闭Excel 进程。
GC.Collect();
}
}
}
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
public partial class Excel : System.Web.UI.Page
{
SQLHelper sqlH;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnExport_Click(object sender, EventArgs e)
{
string str = "SELECT [classID],[className] FROM [SchoolNews].[dbo].[newsClass] ";
string excelName = "KQ";
string createTime = DateTime.Now.ToString("yyyyMMdd");
Export(str,excelName);
}
protected void Export(string str,string excelName)
{
// sqlH = new SQLHelper();
//string str = "SELECT [classID],[className] FROM [SchoolNews].[dbo].[newsClass] ";
SqlConnection sqlCon = new SqlConnection("server=.;database=schoolnews;uid=sa;pwd=;");
sqlCon.Open();
SqlCommand sqlcom = new SqlCommand(str, sqlCon);
System.Data.SqlClient.SqlDataReader sdr = sqlcom.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(sdr);
sdr.Close();
sqlCon.Close();
int[] index = { 0, 1 };
string[] heads = { "classID", "className" };
//string name = Server.MapPath("file/template.xls");
string name = "C:\\excel\\"+excelName+".xlsx";
ExportToExcel(dt, "C:\\excel\\" + excelName + ".xlsx", index, heads);// Server.MapPath("file/template.xls")
System.IO.FileInfo aFile = new System.IO.FileInfo(name);
string na = Path.GetFileName(name);
Response.Clear();
Response.ClearHeaders();
Response.BufferOutput = false;
Response.ContentType = "application/ms-excel";
//Response.AddHeader("Content-Disposition","attachment;filename="+na);
//上面这条中文会乱码,应该下面这样写
Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(na, System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", aFile.Length.ToString());
Response.WriteFile(name);
Response.Flush();
Response.End();
}
public static bool ExportToExcel(System.Data.DataTable table, string excelName, int[] columnIndexs, string[] columnHeads)
{
#region 将方法中用到的所有Excel变量声明在方法最开始,以便最后统一回收。
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass oExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook obook = null;
Microsoft.Office.Interop.Excel.Worksheet oSheet = null;
Microsoft.Office.Interop.Excel.Range range = null;
#endregion
try
{
obook = oExcel.Workbooks.Add("");
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets[1];
int rCount, cCount;
rCount = table.Rows.Count;
cCount = table.Columns.Count;
object obj = System.Reflection.Missing.Value;
if (cCount < columnIndexs.Length || cCount < columnHeads.Length)
{
throw new ArgumentOutOfRangeException("columnIndexs 与 columnHeads 长度必须一致。");
}
for (int i = 1; i <= columnIndexs.Length; i++)
{
//Excel.Range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
range = (Microsoft.Office.Interop.Excel.Range)oSheet.Columns.get_Item(i, obj);
range.NumberFormatLocal = "@";
}
for (int c = 0; c < columnIndexs.Length; c++)
{
oSheet.Cells[1, c + 1] = columnHeads[c];
for (int r = 1; r <= rCount; r++)
{
oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString();
}
}
obook.Saved = true;
obook.SaveCopyAs(excelName);
//必须调用 obook.Close(), 否则无法释放进程。
obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
// 调用System.Runtime.InteropServices.Marshal.ReleaseComObject(object)方法释放方法中
//用到的所有的Excel 变量, 记住是所有的。 比如说此方法中的range 对象, 就容易被遗忘。
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(obook);
// 很多文章上都说必须调用此方法, 但是我试过没有调用oExcel.Quit() 的情况, 进程也能安全退出,
//还是保留着吧。
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
// 垃圾回收是必须的。 测试如果不执行垃圾回收, 无法关闭Excel 进程。
GC.Collect();
}
}
}