如何在WinForm C#中将数据导出到Excel工作表?

时间:2012-12-07 03:02:52

标签: c# winforms excel

这是我的代码:

使用Excel = Microsoft.Office.Interop.Excel;

private void button5_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand();
    int colIndex = 1;
    int rowIndex = 1;
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;
    xlApp = new Excel.Application();
    Con.Open();
    cmd.Connection = Con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from Table1";
    SqlDataReader reader = cmd.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Load(reader);
    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    foreach (DataRow dr in dt.Rows)
    {
        rowIndex = rowIndex + 1;
        colIndex = 0;
        foreach (DataColumn dc in dt.Columns)
        {
            colIndex = colIndex + 1;
            xlWorkSheet.Cells[rowIndex + 1, colIndex] = dr[dc.ColumnName];
        }
    }

    xlApp.Visible = true;
    ObjectRelease(xlWorkSheet);
    ObjectRelease(xlWorkBook);
    ObjectRelease(xlApp);
}

它将所有数据从“Table1”导出到Sheet1。但我想出口:

Row1 => Sheet 1中

Row2 => Sheet 2中

Row3 =>表Sheet 3

...

我如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

查看代码xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);它应该是第一张表。

如果您在循环中拉出该行代码,并将1更改为rowIndex,则应将其连续到表格中。我唯一不知道的是你是否能“获得”尚不存在的表格,所以你可能需要创建新的表格。