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
...
我怎樣才能解決呢?