数据集导出为ex​​cel并在excel中写入多个工作表

时间:2015-01-22 05:29:17

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

我的项目中要求多个数据库表中的数据应按excel文件中的表格导出,如果数据集包含4个表,那么表0应该是国家,表1应该是状态等等......所以请告诉我任何有效的方法,一次将多个数据表导出到excel文件,excel应该在运行时生成。我正在使用C#ASP.NET

1 个答案:

答案 0 :(得分:1)

我只是将新工作簿添加到每个表的工作簿对象中,然后遍历表,将每个工作簿写入工作簿。默认情况下会创建3个工作簿,因此如果数据集中有三个以上的表,则需要删除额外的工作簿。

var ds = [Your dataset here];
Worksheet objWorkSheet1 = null;
Application objExcel = new Application {Visible = false};
Workbooks objWorkbooks = objExcel.Workbooks;
Workbook objWorkbook = objWorkbooks.Add(Missing.Value);
Sheets objSheets = objWorkbook.Worksheets;

if (ds.Tables.Count > objSheets.Count)
{
    // add extra sheets
    for (var i = objSheets.Count; i < ds.Tables.Count; i++)
    {
        var objWorkSheet2 = (Worksheet)objSheets[i];
        objWorkSheet1 = (Worksheet)objSheets.Add(Missing.Value, objWorkSheet2, 1, XlSheetType.xlWorksheet);
        Marshal.ReleaseComObject(objWorkSheet2);
        Marshal.ReleaseComObject(objWorkSheet1);
        objWorkSheet1 = null;
    }
}
while (ds.Tables.Count < objSheets.Count)
{
    // remove unnecessary sheets
    var objWorkSheet2 = (Worksheet)objSheets[ds.Tables.Count];
    objWorkSheet2.Delete();
    Marshal.ReleaseComObject(objWorkSheet2);
}
Range objCells;
Range myCell;
for (var t = 0; t < ds.Tables.Count; t++)
{// for each table in the dataset fill in the sheet 
    var iCurrentRow = 1;
    var dt = ds.Tables[t];
    objWorkSheet1 = (Worksheet)(objSheets[t + 1]);
    objCells = objWorkSheet1.Cells;

    //Start writing the table to the worksheet
    // Get the sheet and write the headers
    for (var h = 0; h < dt.Columns.Count; h++)
    {
        myCell = (Range)objCells[iCurrentRow, h + 1];
        myCell.Value2 = dt.Columns[h].ColumnName;
        Marshal.ReleaseComObject(myCell);
    }
    iCurrentRow++;
    // write the data rows
    for (var r = 0; r < dt.Rows.Count; r++)
    {
        // Get the sheet and write the headers
        for (var c = 0; c < dt.Columns.Count; c++)
        {
            myCell = (Range)objCells[r + iCurrentRow, c + 1];
            myCell.Value2 = dt.Rows[r][c].ToString();
            Marshal.ReleaseComObject(myCell);
        }
    }
    Marshal.ReleaseComObject(objCells);
    objCells = null;
    Marshal.ReleaseComObject(objWorkSheet1);
    objWorkSheet1 = null;
}
//End writing the data table to the sheet

// select the first cell in the first sheet
objWorkSheet1 = (Worksheet)(objSheets[1]);
objCells = objWorkSheet1.Cells;
myCell = (Range)objCells[1, 1];
Marshal.ReleaseComObject(myCell);
myCell = null;
Marshal.ReleaseComObject(objCells);
objCells = null;
Marshal.ReleaseComObject(objWorkSheet1);
objWorkSheet1 = null;

// save the file to the new location with new name.
objWorkbook.Close(true, [your filename here to save to], Missing.Value);

objWorkbooks.Close();
objExcel.Quit();

另一种方法是使用报告服务。报告的每个页面都将以excel的形式呈现给自己的工作表。