我正在使用 Excel 2010。我正在尝试使用此代码保存我的 excel 文件。它确实保存了一个 .xls 文件,但是当我打开该文件时,我收到以下消息:
您尝试打开的文件“tre.xls”的格式与文件扩展名指定的格式不同。在打开文件之前,请确认文件没有损坏并且来自推力源。您现在要打开文件吗?
如果我按yes
文件打开。但是我需要什么来摆脱这种格式弹出窗口?
我的代码:
using System;
using System.Windows.Forms;
using ExcelAddIn1.Classes;
using ExcelAddIn1.Classes.Config;
using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using System.Runtime.InteropServices;
private void Foo(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "Save path of the file to be exported";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// Save.
// The selected path can be got with saveFileDialog.FileName.ToString()
Application excelObj =
(Application)Marshal.GetActiveObject("Excel.Application");
Workbook wbook = excelObj.ActiveWorkbook;
wbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlWorkbookDefault,
Type.Missing, Type.Missing, false, false,
XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
wbook.Close();
}
}
当我以正常方式保存在excel中时,我得到“Book1.xlsx”,打开没有问题。
============= 最终解决方案 =============
private void Foo(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "Save path of the file to be exported";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Application excelObj = (Application)Marshal.GetActiveObject("Excel.Application");
Activate(); // <-- added (recommend by msdn, but maybe not nessary here)
Workbook wbook = excelObj.ActiveWorkbook;
wbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlExcel8, Type.Missing,
Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// wbook.Close(); // <-- don't want this anymore
}
}