导出数据到Excel方法总结

2022-11-18,,,

一,问题的提出

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

二,解决方法

1.       用NPOI导出数据到Excel

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

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

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

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

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

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

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

3.       VBA+ASPX技术实现。

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

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

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

4.       OleDb数据访问技术。

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

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

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

三,具体实现代码

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

1, 用NPOI导出数据到Excel

关键代码:

    public void RenderDataTableToExcel(DataTable SourceTable)
    {
    //创建对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
    HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
    //获得表头名称
    foreach (DataColumn column in SourceTable.Columns)
    {
    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
    }
    //写入数据
    int rowIndex = 1;
    foreach (DataRow row in SourceTable.Rows)
    {
    HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
    foreach (DataColumn column in SourceTable.Columns)
    {
    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
    }
    rowIndex++;
    }
    //保存
    string path = Server.MapPath("~/UpFiles/ReportResult/") + "test.xls";
    FileStream file = new FileStream(path, FileMode.Create);
    workbook.Write(file);
    //关闭文件,释放对象
    file.Close();
    sheet = null;
    headerRow = null;
    workbook = null;
    }

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();

四,总结

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

五,完整代码下载地址

 http://download.csdn.net/source/3149222

导出数据到Excel方法总结的相关教程结束。

《导出数据到Excel方法总结.doc》

下载本文的Word格式文档,以方便收藏与打印。