[英]How to repair an excel file?
我有一个 excel 文件,其中包含 4 个工作表。 外部系统每天发送 excel 个文件,我的程序读取数据然后将数据存储到 db。 我有 3 个文件,当我的程序尝试读取它给出错误“外部表不是预期格式”的文件时,这些文件可能已损坏。 当我尝试在 Office 界面中打开文件时,它返回 Excel 在 file.xlsx 中找到了不可读的内容你想恢复这个工作簿的内容吗? ETC...
当我用 office excel 修复文件并再次保存后启动程序时,它可以工作。 但我需要在程序开始读取之前修复这些文件。 有没有办法像office一样修复excel文件?
我正在使用 Microsoft.ACE.OLEDB.12.0;
您可以使用Excel Interop打开文件并像 Excel 一样进行修复。 但是你不能在没有 MS Office 的机器上使用你的程序。 您可以尝试第三方库,例如:
Excel互操作的代码如下:
Missing missing = Missing.Value;
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(sourceFilePath,
missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,
missing, missing, missing, XlCorruptLoad.xlRepairFile);
workbook.SaveAs(savedFile, XlFileFormat.xlWorkbookDefault,
missing, missing, missing, missing,
XlSaveAsAccessMode.xlExclusive, missing,
missing, missing, missing, missing);
workbook.Close(true, missing, missing);
由于您的文件来自外部来源,因此作为安全预防措施,它可能会被阻止。 解决方案可能是以编程方式解锁 Excel 文件,如下所示:
public class FileUnblocker {
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeleteFile(string name);
public bool Unblock(string fileName) {
return DeleteFile(fileName + ":Zone.Identifier");
}
}
我在使用 Microsoft.Office.Interop.Excel 库时遇到了类似的问题。 Serkan 的回答是完全正确的,它为我指明了正确的方向,但并没有解决我的问题。 在挖掘了一些 Microsoft 博客后,我找到了这个解决方案。 Open() 方法可以采用 3 个不同的常量作为最后一个参数。
对我来说,第三个奏效了。 我必须打开几种不同类型的 excel 文件,其中一些会引发此错误,而另一些不会,因此我将所有内容都包含在 try/catch 中以处理它引发 COMException 的情况。 您可能遇到了不同的异常,但值得尝试我上面提到的每个常量,看看是否能解决问题。
ExcelApp.Workbook excelBook;
ExcelApp._Worksheet excelSheet;
ExcelApp.Range excelRange;
try
{
excelBook = excelApp.Workbooks.Open(path);
excelSheet = excelBook.Sheets[1];
excelRange = excelSheet.UsedRange;
}
catch(COMException)
{
excelBook = excelApp.Workbooks.Open(path, CorruptLoad:
ExcelApp.XlCorruptLoad.xlExtractData);
excelSheet = excelBook.Sheets[1];
excelRange = excelSheet.UsedRange;
}
您可以使用以下代码创建一个宏
Sub OpenAndRepairWorkbook()
Dim oWB As Workbook
On Error GoTo Err_Open
Application.DisplayAlerts = False
Set oWB = Workbooks.Open(Filename:="C:\ShasurData\ExcelVBA\VBE Tools 2007.xlam", CorruptLoad:=XlCorruptLoad.xlRepairFile)
Application.DisplayAlerts = True
Exit Sub
Err_Open:
MsgBox Err.Number & " - " & Err.Description
Err.Clear
Application.DisplayAlerts = True
End Sub
我在这里找到了这个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.