Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table = GetData(index);
//将所得到的表的列名,赋值给单元格
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
//同样方法处理数据
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
//不可见,即后台处理
excel.Visible = false;
excel.UserControl = false;
if (m_strSampleFolder.ToString().Length == 3)
{
excel.ActiveWorkbook.SaveAs(m_strSampleFolder + OutFileName, Excel.XlFileFormat.xlWorkbookNormal, m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
else
{
excel.ActiveWorkbook.SaveAs(m_strSampleFolder + "\\" + OutFileName, Excel.XlFileFormat.xlWorkbookNormal, m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
MessageBox.Show("文件保存成功");