【问题标题】:How to export data to excel sheets in WinForm C#?如何在 WinForm C# 中将数据导出到 Excel 工作表?
【发布时间】:2012-12-07 03:02:51
【问题描述】:

这是我的代码:

使用 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 => Sheet1

Row2 => Sheet2

Row3 => Sheet3

...

我该如何解决这个问题?

【问题讨论】:

    标签: c# winforms excel


    【解决方案1】:

    看代码xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);应该是拿到第一张了。

    如果你在循环中拉出那行代码,并将1 更改为rowIndex,它应该进入连续的工作表。我唯一不知道的是您是否可以“获取”尚不存在的工作表,因此您可能需要创建新工作表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多