最近在office升级为2016之后,原本用com自动生成excel的方法报错了。
格式太旧或是类型库无效。 (异常来自 HRESULT:0x80028018 (TYPE_E_INVDATAREAD)) IP : ::1
Trace : 在 Microsoft.Office.Interop.Excel.WorkbookClass.get_FileFormat()
Microsoft.Office.Interop.Excel.Application excel = null;
Workbook workbook = null;
CultureInfo oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
excel = new Microsoft.Office.Interop.Excel.Application();
CultureInfo newCulture = new CultureInfo(excel.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));
System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
excel.Visible = false;
workbook = excel.Workbooks.Add(templateFile);
运行到这一步的时候报错:workbook = excel.Workbooks.Add(templateFile);
经过反复试验,发现了微软的一个bug。
当我把templateFile文件重命名之后,运行代码时,会报一个找不到文件的错,
然后关掉报错窗口,整个程序别退出,修改回文件名,再点导出文件的时候就成功了。
好神奇!!
bool isFirstTime = true; bool isSuccess = false; while (!isSuccess) { string saveFileName = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), @"temp\" + excelName + ".xlsx"); string templateFile = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), @"template\" + excelName + ".xlsx"); Microsoft.Office.Interop.Excel.Application excel = null; Workbook workbook = null; CultureInfo oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture; excel = new Microsoft.Office.Interop.Excel.Application(); CultureInfo newCulture = new CultureInfo(excel.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI)); System.Threading.Thread.CurrentThread.CurrentCulture = newCulture; excel.Visible = false; if (isFirstTime) { try { workbook = excel.Workbooks.Add(templateFile.Replace(excelName, excelName + "1")); } catch { isFirstTime = false; continue; } } else { workbook = excel.Workbooks.Add(templateFile); } ... }
先让代码报一次找不到文件的错,再正常运行生成excel就成功了!
浙公网安备 33010602011771号