将DataTable导出到Excel

时间:2016-03-02 17:31:29

标签: c# asp.net excel datatable

我有一个小型Web应用程序,可以从jquery datepicker创建两个数据表。如果它们在同一页面上,我可以将这些数据表导出为优秀的。

我已将我的应用程序更改为在新的webforms上呈现数据表。

以下是我要导出到excel的代码:

    protected void ExportToExcel(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            this.BindGrid1(TextDateFrom.Text, TextDateTo.Text);

            GridView2.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in GridView2.HeaderRow.Cells)
            {
                cell.BackColor = GridView2.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in GridView2.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = GridView2.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = GridView2.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }

            GridView2.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }

这是我遇到麻烦的地方:

    this.BindGrid1(TextDateFrom.Text, TextDateTo.Text);

当然我的BindGrid1()是另一种形式。要在我的新表单中调用我的数据表,我创建了一个会话。

如果我在Web表单上有数据表的代码:

     DataTable dt = (DataTable)Session["GridData"];
     if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

我不确定如何称呼它。导出所有页面。我是否应该创建一个全局变量来获取BindGrid1方法中的String值然后在新页面上使用?

1 个答案:

答案 0 :(得分:1)

与您的任务相关,可以使用以下过程实现从DataTable dt到Excel的数据导出,该过程使用Microsoft.Office.Interop.Excel对象库:

/// <summary>
/// export DataTable to Excel (C#)
/// </summary>
internal static void Export2Excel(DataTable dataTable)
{
    object misValue = System.Reflection.Missing.Value;
    Microsoft.Office.Interop.Excel.Application _appExcel = null;
    Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
    Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
    try
    {
        // excel app object
        _appExcel = new Microsoft.Office.Interop.Excel.Application();

        // excel workbook object added to app
        _excelWorkbook = _appExcel.Workbooks.Add(misValue);

        _excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

        // column names row (range obj)
        Microsoft.Office.Interop.Excel.Range _columnsNameRange;
        _columnsNameRange = _excelWorksheet.get_Range("A1", misValue).get_Resize(1, dataTable.Columns.Count);

        // column names array to be assigned to _columnNameRange
        string[] _arrColumnNames = new string[dataTable.Columns.Count];

        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            // array of column names
            _arrColumnNames[i] = dataTable.Columns[i].ColumnName;
        }

        // assign array to column headers range, make 'em bold
        _columnsNameRange.set_Value(misValue, _arrColumnNames);
        _columnsNameRange.Font.Bold = true;

        // populate data content row by row
        for (int Idx = 0; Idx < dataTable.Rows.Count; Idx++)
        {
            _excelWorksheet.Range["A2"].Offset[Idx].Resize[1, dataTable.Columns.Count].Value =
            dataTable.Rows[Idx].ItemArray;
        }

        // Autofit all Columns in the range
        _columnsNameRange.Columns.EntireColumn.AutoFit();
    }
    catch { throw; }
}

只是传递dt作为参数。

希望这可能会有所帮助。