我上一篇文章介紹了Excel導(dǎo)入到DataTable的方法,總覺得少些什么,這篇我就將DataTable
中的數(shù)據(jù)導(dǎo)出到Excel并提供下載的方法記錄下來。
調(diào)用如下:
CreateExcel(dtexcel, "application/ms-excel", excel);
方法如下:
/// <summary>
/// DataTable中的數(shù)據(jù)導(dǎo)出到Excel并下載
/// </summary>
/// <param name="dt">要導(dǎo)出的DataTable</param>
/// <param name="FileType">類型</param>
/// <param name="FileName">Excel的文件名</param>
public void CreateExcel(DataTable dt, string FileType, string FileName)
{
Response.Clear();
Response.Charset = "UTF-8";
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
Response.ContentType = FileType;
string colHeaders = string.Empty;
string ls_item = string.Empty;
DataRow[] myRow = dt.Select();
int i = 0;
int cl = dt.Columns.Count;
foreach (DataRow row in myRow)
{
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
ls_item += row[i].ToString() + "\n";
}
else
{
ls_item += row[i].ToString() + "\t";
}
}
Response.Output.Write(ls_item);
ls_item = string.Empty;
}
Response.Output.Flush();
Response.End();
}
asp.net 將Excel中某個(gè)工作簿的數(shù)據(jù)導(dǎo)入到DataTable方法最近在網(wǎng)上看了幾篇將Excel中某個(gè)工作簿的數(shù)據(jù)導(dǎo)入到DataTable的文章,自己總結(jié)了一套最實(shí)用的方法。
這里需要注意的是:從Excel的導(dǎo)入到DataTable時(shí),Excel的第一行數(shù)據(jù)會(huì)導(dǎo)入成DataTable的字段,所以
Excel的第一行最好可以為空或者標(biāo)識(shí)數(shù)據(jù)。
添加引用:
using System.Data.OleDb;
using System.IO;
調(diào)用如下:
DataTable dt = GetExcelData("D:\\Data.xls", "sheet1");
方法如下:
/// <summary>
/// 獲取指定路徑、指定工作簿名稱的Excel數(shù)據(jù)
/// </summary>
/// <param name="FilePath">文件存儲(chǔ)路徑</param>
/// <param name="WorkSheetName">工作簿名稱</param>
/// <returns>如果爭取找到了數(shù)據(jù)會(huì)返回一個(gè)完整的Table,否則返回異常</returns>
public DataTable GetExcelData(string FilePath, string WorkSheetName)
{
DataTable dtExcel = new DataTable();
OleDbConnection con = new OleDbConnection(GetExcelConnection(FilePath));
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [" + WorkSheetName + "$]", con);
//讀取
con.Open();
adapter.FillSchema(dtExcel, SchemaType.Mapped);
adapter.Fill(dtExcel);
con.Close();
dtExcel.TableName = WorkSheetName;
//返回
return dtExcel;
}
/// <summary>
/// 獲取鏈接字符串
/// </summary>
/// <param name="strFilePath"></param>
/// <returns></returns>
public string GetExcelConnection(string strFilePath)
{
if (!File.Exists(strFilePath))
{
throw new Exception("指定的Excel文件不存在!");
}
return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended properties=\"Excel 8.0;Imex=1;HDR=Yes;\"";
//@"Provider=Microsoft.Jet.OLEDB.4.0;" +
//@"Data Source=" + strFilePath + ";" +
//@"Extended Properties=" + Convert.ToChar(34).ToString() +
//@"Excel 8.0;" + "Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}