日期:2014-05-18  浏览次数:20791 次

C#导数据到excel的问题
code如下,生成xlsx文件一切正常,但是xls会出现“您尝试打开的**.xls的格式与文件扩展名指定的格式不一致”。
请问这是为什么了?

[code=C#][/code]
private void ExtractResult_Click(object sender, EventArgs e)
  {
  //由于使用的是COM库,因此有许多变量需要用Nothing 代替 
  Object Nothing = Missing.Value;
  //WdSaveFormat 为Excel文档的保存格式 
  object format = Excel.XlFileFormat.xlOpenXMLWorkbook;
  Excel.XlFileFormat version = Excel.XlFileFormat.xlExcel8;
  SaveFileDialog saveexcel = new SaveFileDialog();
  saveexcel.Filter = "文件类型(*.xlsx)|*.xlsx|文件类型(*.xls)|*.xls";
  if (saveexcel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  {
  string path = saveexcel.FileName;//文件路径变量 
  if (System.IO.Path.GetExtension(saveexcel.FileName).ToLower() == ".xlsx")
  {
  version = Excel.XlFileFormat.xlOpenXMLWorkbook;
  }
  if (System.IO.File.Exists(path))
  {
  System.IO.File.Delete(path);
  }
  try
  {
  Excel.Application excelApp = new Excel.Application(); //Excel应用程序变量 
  Excel.Workbook excelDoc = excelApp.Workbooks.Add(Nothing); //Excel文档变量
  Excel.Worksheet sheet = (Excel.Worksheet)excelDoc.Sheets[1];
  sheet.Cells[1, 1] = "123";
  //将 excelDoc文档对象的内容保存为XLSX文档  
  excelDoc.SaveAs(path, Nothing, Nothing, Nothing, Nothing, Nothing, Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
  //关闭excelDoc文档对象 
  excelDoc.Close(Nothing, Nothing, Nothing);
  //关闭excelApp组件对象  
  excelApp.Quit();
  MessageBox.Show(path.ToString() + " 导出成功");
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  }
  }

------解决方案--------------------
if (System.IO.Path.GetExtension(saveexcel.FileName).ToLower() == ".xlsx" || System.IO.Path.GetExtension(saveexcel.FileName).ToLower() == ".xls" )
{
version = Excel.XlFileFormat.xlOpenXMLWorkbook;
}

没细看,,先试试