如果保存生成的excel文件提示如下错误,
可以通过设置保存excel格式来解决。
【例】
public static string xlsFilePath = @"D:\";//excel文件存放路径
/// <summary>
/// 导出数据到excel文件
/// </summary>
/// <param name="dt">要导出的数据集</param>
/// <returns>生成的文件名</returns>
static public string ExporeToExcel(DataTable dt)
{
MSExcel.Application excelApp = null;
MSExcel.Workbooks wbks = null;
MSExcel._Workbook wbk = null;
try
{
string strDir = Directory.GetCurrentDirectory();
excelApp = new MSExcel.Application();
excelApp.Visible = false;//是打开不可见
wbks = excelApp.Workbooks;
wbk = wbks.Add(true);
String version = excelApp.Version;//获取你使用的excel 的版本号
int FormatNum;//保存excel文件的格式
if (Convert.ToDouble(version) < 12)//You use Excel 97-2003
{
FormatNum = -4143;
}
else//you use excel 2007 or later
{
FormatNum = 56;
}
object Nothing = Missing.Value;
MSExcel._Worksheet whs;
whs = (MSExcel._Worksheet)wbk.Sheets[1];//获取第一张工作表
whs.Activate();
//写入标题行
int rowIndex=1;
for (int col = 0; col < dt.Columns.Count; col++)
{
whs.Cells[rowIndex, col+1] = dt.Columns[col].Caption.ToString();
}
rowIndex++;
//写入数据内容
foreach (DataRow row in dt.Rows)
{
for (int colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
{
whs.Cells[rowIndex, colIndex + 1] = row[colIndex].ToString();
}
rowIndex++;
}
excelApp.DisplayAlerts = false;
//保存excel文件
string newFileName = xlsFilePath + "导出的excel文件" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
wbk.SaveAs(newFileName, FormatNum);//保存时候设置保存格式
//关闭文件
wbk.Close(false, Nothing, Nothing);
return newFileName;
}
catch (Exception e)
{
throw e;
}
finally
{
//wbks.Close();//关闭工作簿
excelApp.Quit();//关闭excel应用程序
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);//释放excel进程
excelApp = null;
}
}