如何将数据导出到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
Row2 => Sheet2
Row3 => Sheet3
…
我如何解决这个问题?
看代码xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
应该是得到第一张。
如果你在你的循环内部拉出那行代码,把1
改为rowIndex
,它应该进入连续的表单。 我唯一不知道的是是否可以“获取”尚不存在的工作表,因此您可能需要创build新工作表。