求一段代码:
1 把DataTable的内容导出到excel中!
2 用户点击一个按钮,给用户下载这个excel文件
1 把DataTable的内容导出到excel中!
2 用户点击一个按钮,给用户下载这个excel文件
解决方案 »
- 怎么让链接不再出现???
- 多次登录或者异点登录的问题
- activereport 报表打印 如何判断textbox控件中的字符宽度是否超出控件的宽度
- 关于vs2008 安装后 iis 的问题
- 2道ASP.Net选择题 帮忙选一下.
- 是否一定要将。NET程序设置为应用程序(即放在根目录),才能运行?
- 请教 高手 关于通过textbox 创建自定义搜索功能 感兴趣的高手详细指导下.....
- 关于名称空间的问题!!!
- 怎么实现类似于新闻组或水木那种效果的论坛
- 求ASP.NET连接mysql的方法,请高人指点!
- 关于javascript向ASP.net程序传值的问题
- 返回查询页面并保持原来的查询条件和数据
把网页另存为txt文件就可以了
private void TransferExcel()
{
Excel.Application oExcel= new Excel.ApplicationClass();
Excel.Workbook oBook ;
Excel.Workbooks oBooks;
Excel.Worksheet oSheet;
Excel.Sheets oSheets;
Excel.Range oCells;
string sFile,sTemplate;
object Nothing = System.Reflection.Missing.Value;
//定义一个datatable
DataTable objDataTable = new DataTable();
//把DataGrid中的数据导入datatable中
objDataTable = (DataTable)Session["objDataTable"];
sFile = Server.MapPath(Request.ApplicationPath) + "\\Excel\\MyExcel"+Request.Cookies["StaffID"].Value.ToString()+".xls";
//定义模版文件
sTemplate = Server.MapPath(Request.ApplicationPath) + "\\Excel\\MyTemplate.xls";
oExcel.Visible = false;
oExcel.DisplayAlerts = false;
//定义一个新的工作簿
oBooks = oExcel.Workbooks;
oBooks.Open(Server.MapPath(Request.ApplicationPath) + "\\Excel\\MyTemplate.xls",Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing);
oBook = oBooks[1];
oSheets = oBook.Worksheets;
oSheet = (Excel.Worksheet)oSheets[1];
//命名该sheet
oSheet.Name = "工资表";
oCells = oSheet.Cells;
//调用dumpdata过程,将数据导入到Excel中去
DumpData(objDataTable, oCells);
//保存
oSheet.SaveAs(sFile,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing);
oBook.Close(false,Nothing,Nothing); //退出Excel,并且释放调用的COM资源;
oExcel.Quit();
Marshal.ReleaseComObject(oCells);
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oSheets);
Marshal.ReleaseComObject(oBook);
Marshal.ReleaseComObject(oBooks);
Marshal.ReleaseComObject(oExcel);
oExcel = null;
oBooks = null;
oBook = null;
oSheets = null;
oSheet = null;
oCells = null;
System.GC.Collect();
Response.Redirect(sFile);
}
private void DumpData(DataTable dt,Excel.Range oCells)
{
int i,iCol,iRow;
//输出列标题
for(iCol=0;iCol < dt.Columns.Count;iCol++)
{
oCells[1,iCol+1] = dt.Columns[iCol].ToString();
}
//Response.Write("\n");
//将数据导出到相应的单元格
for(iRow=0;iRow <dt.Rows.Count;iRow++)
{
for(i=0;i<dt.Columns.Count;i++)
{
oCells[iRow+2,i+1] = dt.Rows[iRow].ItemArray[i].ToString();
Response.Write(dt.Rows[iRow].ItemArray[i].ToString()+"\t");
}
}
}
由于我们要使用的是Excel,所以添加一个关于COM的应用,这里添加的是Microsoft Excel Object Library。
在代码上面加入:
using System.Runtime.InteropServices;
using Microsoft.Office;
我现在用的很正常!