请问,DataTable导出EXCEL
在网上搜了好久,找到个简单点的:public void SetExcelFromData(System.Data.DataTable dt, string FileName)
{
StringWriter sw = new StringWriter();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(dt.Columns[i].ColumnName);
if (i != dt.Columns.Count - 1)
{
sb.Append(",");
}
}
sw.WriteLine(sb.ToString());
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dr[i]);
if (i != dt.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.WriteLine("");
}
sw.Close();
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Context.Server.UrlEncode(FileName) + ".csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.Write(sw);
Response.End();
}
问题:
为什么报错呢?说当前上下文不存在Response和Context
我还看不懂,想先照搬下来,在使用 --------------------编程问答-------------------- 在这个类中没有引用
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
将这三个加上一定可以 --------------------编程问答-------------------- Response是以HttpResponse的形式下载文件的语句,这里只是要DataTable导出EXCEL,这部分代码不需要 --------------------编程问答-------------------- http://blog.csdn.net/happy09li/article/details/7431967 --------------------编程问答-------------------- 没有引用相关的dll,在提供另一种将数据显示在excel中的方法
http://blog.csdn.net/bdmh/article/details/5857470 --------------------编程问答-------------------- 实现,你的程序是用于WINFORM还是WEB的,如果是WINFORM,你这个可以放弃了。其次,IDE再用熟练点吧。 --------------------编程问答-------------------- 简单点的倒是容易,用DataTable读取Excel不过无法读取合并单元格的 。。。要下班了,给你写个...自己看着办
--------------------编程问答-------------------- 同意6樓,剛看了下c/s下的response還真沒看到怎麼引用出來,繞過它
/// <summary>
/// 读取标准的Excel文件返回DataTable(合并单元格未提供)
/// </summary>
/// <param name="Path">Excel所在的路径</param>
/// <param name="Sheet">Excel中的表的名称,若为默认名称则传入空字符串</param>
/// <returns>返回DataTable</returns>
public DataTable ReadToDataTable(string Path,string Sheet)
{
DataTable dt = new DataTable();
try
{
string SheetName = Sheet == null ? "sheet1" : Sheet;
string Constr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", Path);
string SQL = "select * from [" + SheetName + "$]";
using (OleDbConnection conn = new OleDbConnection(Constr))
{
OleDbDataAdapter da = new OleDbDataAdapter(SQL, conn);
da.Fill(dt);
}
}
catch
{
throw;
}
return dt;
}
补充:.NET技术 , C#