2012-12-07 406 views
0

這裏我的代碼:如何將數據導出到WinForm C#中的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 =>工作表Sheet1

行2 => Sheet2中

ROW3 =>表Sheet 3

...

我怎樣才能解決呢?

回答

2

看代碼xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);它應該得到第一張。

如果您在循環中拉出該行代碼,並將1更改爲rowIndex,則應將其連續放入工作表中。我唯一不知道的是你是否可以'獲取'尚不存在的工作表,因此您可能需要創建新工作表。

相關問題