//需要在bin里面添加 Interop.Microsoft.Office.Interop.Excel.dll 的引用
//添加引用
using System.Data;
/// <summary>
/// 导出数据到Excel
/// </summary>
/// <param name="strWhere">查询条件</param>
/// <param name="returnMsg"></param>
/// <returns></returns>
public bool ExportOrderToExcel(string strWhere, ref string returnMsg)
{
try
{
DataTable dt = “DataTable 的数据集”;
if (dt != null && dt.Rows.Count > 0)
{
int rowNumber = dt.Rows.Count;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;//是否打开该Excel文件
//填充数据
for (int c = 0; c <= rowNumber; c++) //行
{
for (int j = 0; j < 6; j++)//列
{
if (c == 0) //表头
{
if (j == 0)
{
excel.Cells[c + 1, j + 1] = "";//表头名称
}
else if (...)
{
excel.Cells[c + 1, j + 1] = "";
}
}
else //填充内容
{
excel.Cells[c + 1, j + 1] = dt.Rows[c-1][j];
}
}
}
returnMsg = "1,";//导出成功
return true;
}
else
{
returnMsg = "2,没有查到要导出的数据!";
return false;
}
}
catch (Exception)
{
returnMsg = "2,导出数据失败!";
return false;
}
}