/// <summary>
/// 将数据导入到Excel
/// </summary>
/// <param name="ds">
/// 需要生成Excel的数据源
/// DataSet->DataTable->TableName为页(Sheet)名字
/// DataTable->Column->ColumnName为列名
/// </param>
/// <param name="strFilenamePath">生成后文件保存的全路径</param>
/// <returns></returns>
public bool ImportToExcel(DataSet ds, string strFilenamePath)
{
if (ds.Tables.Count == 0)
return false;
try
{
Microsoft.Office.Interop.Excel.ApplicationClass objApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel._Workbook objWorkbook;//工作薄
Microsoft.Office.Interop.Excel._Worksheet objWorksheet;//工作页
objWorkbook = objApp.Workbooks.Add(true);
object objMissing = System.Reflection.Missing.Value;
#region 添加数据
for (int i = 0; i < ds.Tables.Count; i++)
{
objWorksheet = (Microsoft.Office.Interop.Excel._Worksheet)objWorkbook.ActiveSheet;
//书签名字为表名
objWorksheet.Name = ds.Tables[i].TableName;
//第一行显示表的列名
for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
{
objApp.Cells[1, j + 1] = ds.Tables[i].Columns[j].ColumnName;
}
//正文内容,从第二行开始
for (int rows = 0; rows < ds.Tables[i].Rows.Count; rows++)
{
for (int cols = 0; cols < ds.Tables[i].Columns.Count; cols++)
{
objApp.Cells[rows + 2, cols + 1] = ds.Tables[i].Rows[rows][cols].ToString();
}
}
if (i < ds.Tables.Count - 1)
{
objApp.Sheets.Add(objMissing, objMissing, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
}
}
#endregion
objApp.Visible = true;
//将Excel保存到指定路径
objWorkbook.SaveAs(
strFilenamePath, objMissing, objMissing, objMissing, objMissing,
objMissing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, objMissing,
objMissing, objMissing, objMissing, objMissing);
objApp.Quit();
return true;
}
catch (Exception ex)
{
string strEXMessage = ex.Message;
return false;
}
}
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)