.net mvc中使用EPPlus操作excel,如果文件不存在则创建文件添加一个sheet保存,但是报保存失败,如果先创建好文件就没问题,奇怪的是放winform里面就没这个问题
try
{
char driveLetter = 'E'; // 要检查的盘符
DriveInfo drive = new DriveInfo(driveLetter + ":");
//盘符存在
if (drive.IsReady)
{
string folderPath = @"E:\数据保存\" + DateTime.Now.ToString("yyyyMM"); // 指定文件夹路径
// 检查文件夹是否已存在,如果不存在则创建
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
string fileName = folderPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
if (!File.Exists(fileName))
{
// 新建 Excel 文件
File.Create(fileName);
}
FileInfo fileInfo = new FileInfo(fileName);
// 添加认证,必填
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("sheet1");
excelPackage.SaveAs(fileInfo);
}
}
}
catch (Exception e)
{
throw e;
}