从SQL Server表数据创建Excel工作表

时间:2014-06-16 12:44:00

标签: c# asp.net sql sql-server excel

我根据从SQL Server检索到的数据动态创建Excel工作表 点击按钮和功能。目前一切正常,因为我有300多条记录,但我担心更多记录的表现。

如果我有大约10,000条记录,我需要对代码进行哪些修改,以便在动态创建页面时不会遇到任何错误?

以下是我使用的代码:

protected void Button1_Click(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(connectionString))
    {

        SqlCommand cmd = new SqlCommand("usp_myReport", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        Excel_FromDataTable(dt);
        Label1.Text = "Excel file created";
    }
}

以下是功能:

private static void Excel_FromDataTable(DataTable dt)
{

    Excel.Application excel = new Excel.Application();
    Excel.Workbook workbook = excel.Application.Workbooks.Add(true);

    int iCol = 0;
    string[] colNames = new string[dt.Columns.Count];
    foreach (DataColumn c in dt.Columns)
    {
        colNames[iCol++] = c.ColumnName;
        char lastColumn = (char)(65 + dt.Columns.Count - 1);
        excel.get_Range("A1", lastColumn + "1").Value2 = colNames;
       }

    int iRow = 0;
    foreach (DataRow r in dt.Rows)
    {
        iRow++;
                    iCol = 0;
        foreach (DataColumn c in dt.Columns)
        {
            iCol++;
            excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
        }
    }

    object missing = System.Reflection.Missing.Value;

    workbook.SaveAs("MyExcelWorkBook.xls",
        Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
        false, false, Excel.XlSaveAsAccessMode.xlNoChange,
        missing, missing, missing, missing, missing);
    excel.Visible = true;
    Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
    ((Excel._Worksheet)worksheet).Activate();
    ((Excel._Application)excel).Quit();

}

1 个答案:

答案 0 :(得分:0)

试试这个

在DataTable中获取数据,然后使用此功能

 public void ExportToExcel_AsXlsFile(DataTable dt, string file_name)
        {
            var grid = new GridView();
            grid.DataSource = dt;
            grid.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename='" + file_name + "'.xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grid.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }