温伟的程序生活,一步一个脚印
自己会努力,做真正独一无二的温伟!无论前方有多难,我都不会放弃... 每一篇日志,都是我的积累,全是我的原创!

导出EXCEL,分三种情景,ASP、ASP.NET、Winform。原理都不一样。
一:ASP主要是通过创建控件来写入,关键代码如下:

1 set fso=CreateObject("Scripting.FileSystemObject")
2 if fso.FileExists(server.mappath(newfile)) then
3     fso.DeleteFile server.mappath(newfile)
4 end if
5 set exc = fso.OpenTextFile(server.mappath(newfile),2,True)
6 exc.write(String)
7 //String is the document to excel,row in String is"chr(13)",Column in String is "chr(9)"

输出的字符例如:zhangsanchar(9)19char(9)女char(13)wangwuchar(9)20char(9)男char(13)...
二:ASP.NET主要也是通过字符串,与ASP不同的是,.NET不用创建文件对象,如关键代码:

HttpResponse hresp;
hresp = Page.Response;
hresp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
hresp.AppendHeader("Content-Disposition", "attachment;filename=" + newfile);
StringBuilder sbItem = new StringBuilder();
//sbItem is the string to excel;Row in sbItem is "\n";Column in sbItem is "\t"
hresp.Write(sbItem.ToString());
hresp.End();

输出的字符例如:zhangsan\t19\t女\nwangwu\t20\t男\n...
三:Winform与ASP(.net)不同,Winform是在客户端运行。而ASP(.NET)是在服务器端运行,以ms-execl的格式通过RESPONSE然后输出到浏览器。而Winform是在客户端调用安装的OFFICE组件,将数据写到工作簿中:

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
            sfd.Title = "Excel文件导出";
            string fileName = "";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                fileName = sfd.FileName;
                if (app == null)
                {
                    MessageBox.Show("Excel启动失败!");
                    return;
...
xlWorkSheet.Cells[a + 1, 1] = dtsub.Rows[a]["CompanyCode"].ToString();
...
xlWorkBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(true, Type.Missing, Type.Missing);
xlWorkSheet = null;
xlWorkBook = null;
app.Quit();

在ASP.NET也能用Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
只是需要设置服务器的组件服务:通过命令dcomcnfg打开组件服务的DCOM配置Microsoft Excel Application 属性,安全选项全部设置为自定义,增加用户Everyone权限最大。标识选项为交互式用户。

这三种情况,应该差不多够用了。

posted on 2013-04-12 11:26  winvay  阅读(250)  评论(0)    收藏  举报