这是我的代码:
使用 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。但我想导出:
第 1 行 => 表 1
第 2 行 => 表 2
第 3 行 => 表 3
...
我该如何解决这个问题?