用EPPlus读取转换后的xlsx时出现的这个问题,以为EPPlus包不行,换了其他包也读取不了.
手动打开xls文件发现页面弹出
"导出的excel文件格式和扩展名不匹配,文件可能已损坏或不安全。除非您信任其来源,否则请勿打开.是否仍要打开它?"
才发现是文件本身的问题
具体操作:
手动用Excel打开,出现弹窗,点击确定,将该文件另存为文件A,再用程序打开文件A,一切正常,代码大体就是这个意思,解决这个问题必须要安装微软的Office或者单独安装Excel组件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.XPath;
using Microsoft.Office.Interop.Excel;
using module.kefu.entities;
using Utils;
namespace module.insured.ManualRemittance.entity
{
class MicsoftExcelUtil
{
/*
* 引用 Microsoft.Office.Interop.Excel 将xls另存为新的xls文件
* 解决"导出的excel文件格式和扩展名不匹配,文件可能已损坏或不安全。除非您信任其来源,否则请勿打开.是否仍要打开它?
*/
public static void SaveAsOtherFile(string filePath,string newFilePath)
{
Application app = null;
Workbook workbook = null;
try
{
app = new Application();
workbook = app.Workbooks.Open(filePath);
//获取当前用户使用Excel的版本号
string version = app.Version;
// 保存文件的格式
int formatNum;
if (Convert.ToDouble(version) < 12) // 97-2003
{
formatNum = -4143;
}
else
{
formatNum = 56; // 2007 or later
}
workbook.SaveAs(newFilePath, formatNum);
}
catch (Exception e)
{
LogUtils.info("xls文件另存为异常:"+e.Message);
throw new Exception("xls文件另存为错误:"+e.Message);
}
finally
{
workbook.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
}
}
}
}