导出数据到Excel方法总结

导出数据到Excel方法总结

一,问题的提出

近来在网上经常有人问怎样把数据导出到Excel中?针对这个问题网上也有很多资料。大都比较的琐碎。本人当前从事的项目中,刚好涉及到这些内容。就顺便做了一些归纳整理。共享给大家。避免大家再花费很多时间研究这个老生长谈的问题。

二,解决方法

  1. 1.       用NPOI导出数据到Excel

简介:NPOI是一个开源的dotnet类库,官方网站:http://npoi.codeplex.com/

优点:支持Excel 2003格式,读写速度快,基于.NET 2.0

缺点:不支持Excel 2007以上版本文件,功能有限,有时Excel宏会被破坏,可能是NPOI的Bug。

  1. 2.       微软Excel,Com组件技术。

简介:利用微软提供的程序集Microsoft.Office.Interop.Excel,dll和Office.dll.必须安装Office软件。

优点:功能强大,有很多官方资料可以参考。支持office2003,2007等版本。

缺点:访问速度慢。有时残留Excel进程问题。

  1. 3.       VBA+ASPX技术实现。

简介:VBA相信大家并不陌生,即是我们常说的Excel中的宏。

优点:很容易控制Excel,实现Excel的高级应用。

缺点:VBA必须与Excel共存。寄生与Excel文件中,移植性很差。

  1. 4.       OleDb数据访问技术。

简介:OleDb是微软提供的一种数据访问技术。

优点:为用户提供了一种统一的方法来访问所有不同种类的数据源。能够利用SQL查询优势。

缺点:OleDb依赖于数据驱动的支持。容易破坏Excel文件,Excel中的sheet被看作数据源,相当于数据库中的表。Excel单元格中的批注无法读取。

5.直接导出DataGrid中的数据:

三,具体实现代码

基本思路都是,打开文件—>写文件—>关闭文件。

1, 用NPOI导出数据到Excel

关键代码:

 

01.public void RenderDataTableToExcel(DataTable SourceTable)  
02.       {  
03.           //创建对象  
04.           HSSFWorkbook workbook = new HSSFWorkbook();  
05.           HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();  
06.           HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);  
07.           //获得表头名称  
08.           foreach (DataColumn column in SourceTable.Columns)  
09.           {  
10.               headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);  
11.           }  
12.           //写入数据  
13.           int rowIndex = 1;  
14.           foreach (DataRow row in SourceTable.Rows)  
15.           {  
16.               HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);  
17.               foreach (DataColumn column in SourceTable.Columns)  
18.               {  
19.                   dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());  
20.               }  
21.               rowIndex++;  
22.           }  
23.           //保存  
24.           string path = Server.MapPath("~/UpFiles/ReportResult/") + "test.xls";  
25.           FileStream file = new FileStream(path, FileMode.Create);  
26.           workbook.Write(file);  
27.           //关闭文件,释放对象  
28.           file.Close();  
29.           sheet = null;  
30.           headerRow = null;  
31.           workbook = null;  
32.       }  


 

2, 微软Excel,Com组件技术。

关键代码:

 

 [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);
        protected void Button1_Click(object sender, EventArgs e)
        {
            //文件路径
            string path = Server.MapPath("~/UpFiles/ReportTemplate/") + "test1.xlsx";
            //写入Excel的数据
            List<string> lst = new List<string>();
            lst.Add("A12");
            lst.Add("A22");
            lst.Add("A32");
            lst.Add("A42");
            lst.Add("A55");
            lst.Add("A5");
            //定义Excel操作对象
            Microsoft.Office.Interop.Excel.Application app;
            Microsoft.Office.Interop.Excel.Workbook workBook;
            Microsoft.Office.Interop.Excel.Worksheet workSheet;
            //创建一个Application对象并使其可见 
            app = new Microsoft.Office.Interop.Excel.ApplicationClass();
            app.Visible = false;
            object missing = Missing.Value;
            //打开文件,得到WorkBook对象 
            workBook = app.Workbooks.Open(path, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            //得到WorkSheet对象 
            workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(2);
            for (int j = 0; j < lst.Count; j++)
            {
                //写入单元格
                workSheet.Cells[j + 1, 1] = lst[j];
            }
            //保存
            workBook.Save();
            //杀Excel进程。
            IntPtr t = new IntPtr(app.Hwnd);
            int k = 0;
            GetWindowThreadProcessId(t, out   k);
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();
        }

 

 

 

3, VBA+ASPX技术实现。

关键代码:

 
Sub SendRequest(xmlRequest As String)
        Dim dom As New MSXML2.DOMDocument
        Dim httprequest As MSXML2.XMLHTTP30
        Dim asp_server As String
        Set httprequest = New MSXML2.XMLHTTP30
        '发送到服务器地址
        asp_server = "http://localhost:1408/VBAExcelGetData.aspx"
        'POST到服务器
        httprequest.Open "POST", asp_server, False
        httprequest.send xmlRequest
        If httprequest.Status = 200 Then
            dom.LoadXML (httprequest.responseXML.XML)
        End If

    '显示结果
    Dim k, j As Integer
    Dim s_Value As String
    
    k = dom.SelectSingleNode("Results").ChildNodes.Length
    If k > 0 Then
   
      For j = 0 To k - 1
         For i = 0 To 7
            s_Value = dom.SelectSingleNode("Results").ChildNodes(j).Attributes(i).NodeValue
            Sheets("结果表").Cells(j + 1, i + 1).Value = s_Value
         Next
      Next
        Application.CutCopyMode = False
        Sheets("结果表").Select
        Sheets("结果表").Range("A1").Select
    End If

    Set dom = Nothing
    Set httprequest = Nothing
End Sub

 

 

4, OleDb数据访问技术。

关键代码:

 //连接
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=no;IMEX=0'";
                OleDbConnection conn = new OleDbConnection(strConn);
                //打开连接
                conn.Open();
                System.Data.OleDb.OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;
                for (int i = 0; i < Lst.Count; i++)
                {
                    cmd.CommandText = "INSERT INTO [sheet1$] (F1) VALUES('" + Lst[i] + "')";
                    //执行Sql
                    cmd.ExecuteNonQuery();
                }
                //关闭连接
                conn.Close();

 5.直接导出DataGrid中的数据

public void DGToExcel(System.Web.UI.Control ctl)   




        {  
            HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls"); 
            HttpContext.Current.Response.Charset ="gb2312";     
            HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.ContentType ="application/ms-excel";
            ctl.Page.EnableViewState =false;    
            System.IO.StringWriter tw = new System.IO.StringWriter() ; 
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw); 
            ctl.RenderControl(hw); 
            HttpContext.Current.Response.Write(tw.ToString()); 
            HttpContext.Current.Response.End(); 
        }

 

   

 

四,总结

这四种方法各有优缺点,需要结合实际情况选择。够用就行。

 

posted @ 2013-04-19 15:49  心随所愿2012  阅读(314)  评论(0编辑  收藏  举报