1 用Microsoft.Office.Interop.Excel,需要window运行环境,并且存在office.excel组件才能运行
2 这里用form表单提交的IFormFile对象作为整个函数的输入对象,需要将 IFormFile对象作为.xlsx文件保存在临时的文件夹中,也可以直接用路径处理,直接从步骤 3 开始:
// 保存文件到临时位置
string fileName = file.FileName;
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);string tempFilePath = Path.Combine(AppContext.BaseDirectory,"PathToSave", fileName);
Stream stream1 = file.OpenReadStream();
using (var stream = new FileStream(tempFilePath, FileMode.Create))
{
await stream1.CopyToAsync(stream);
}
stream1.Close();
3 officeApi根据路径读取文件:
Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(Path.GetFullPath(tempFilePath));
4 我这里单独设置 文件中第二个sheet表的格式是缩放80%,横向布局:
// 获取第二个工作表 第二个材料表需要设置格式
int totalSheets = workbook.Sheets.Count;// 获取Sheets的总数,这包括Worksheet、Chart等所有类型的Sheets
if (totalSheets > 1)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[2];
worksheet.PageSetup.Zoom = 80; // 10 到 400之间的数字 表示打印的缩放程度worksheet.PageSetup.Orientation = XlPageOrientation.xlPortrait; //纵向打印
}
5 指定文件路径(里面包括名称),workbook.ExportAsFixedFormat输出
// 指定导出的PDF文件的目录和文件名
string outputDirectory = AppContext.BaseDirectory;
string outputFileName = fileNameWithoutExtension + ".pdf";
string outputFilePath = System.IO.Path.Combine(outputDirectory,"PathToSave", outputFileName);workbook.ExportAsFixedFormat(fileType, outputFilePath, quality, IncludeDocProperties: false, IgnorePrintAreas: false);
6 完整的代码:
//这里用form表单提交的IFormFile对象
private async Task<List<string>> TransferXLSToPDF(List<IFormFile> files)
{
List<string> pathList = new List<string>();
foreach (var file in files)
{
if (file.Length > 0)
{
// 创建 Excel 应用程序对象
Application excelApp = new Application();
try
{
// 保存文件到临时位置
string fileName = file.FileName;
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
string tempFilePath = Path.Combine(AppContext.BaseDirectory,"PathToSave", fileName);
Stream stream1 = file.OpenReadStream();
using (var stream = new FileStream(tempFilePath, FileMode.Create))
{
await stream1.CopyToAsync(stream);
}
stream1.Close();
Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(Path.GetFullPath(tempFilePath));
// 获取第二个工作表 第二个材料表需要设置格式
int totalSheets = workbook.Sheets.Count;// 获取Sheets的总数,这包括Worksheet、Chart等所有类型的Sheets
if (totalSheets > 1)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[2];
worksheet.PageSetup.Zoom = 80; // 10 到 400之间的数字 表示打印的缩放程度
worksheet.PageSetup.Orientation = XlPageOrientation.xlPortrait; //纵向打印
}
// 将 Excel 文件保存为 PDF
XlFixedFormatQuality quality = XlFixedFormatQuality.xlQualityStandard; // 可根据需要调整质量
XlFixedFormatType fileType = XlFixedFormatType.xlTypePDF;
// 指定导出的PDF文件的目录和文件名
string outputDirectory = AppContext.BaseDirectory;
string outputFileName = fileNameWithoutExtension + ".pdf";
string outputFilePath = System.IO.Path.Combine(outputDirectory,"PathToSave", outputFileName);
workbook.ExportAsFixedFormat(fileType, outputFilePath, quality, IncludeDocProperties: false, IgnorePrintAreas: false);
pathList.Add(outputFilePath);
// 关闭工作簿和 Excel 应用程序
workbook.Close(false);
excelApp.Quit();
excelApp = null;
}
catch (Exception ex)
{
Console.WriteLine($"转换过程中发生错误:{ex.Message}");
}
finally
{
// 释放 COM 对象
if (excelApp != null)
{
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelApp = null;
如果你想强制结束Excel进程(不推荐),你可以这样做:
注意:这可能会影响到其他Excel实例,因此请确保这是你想要的行为
//Process[] excelProcesses = Process.GetProcessesByName("EXCEL");
//foreach (Process process in excelProcesses)
//{
// // 在这里,你可能需要添加一些逻辑来确定哪个Excel进程是你想要结束的
// // 例如,通过检查进程启动时间或其他属性
// // 强制结束Excel进程
// process.Kill();
// process.WaitForExit(); // 等待进程真正退出
//}
}
}
}
}
return pathList;
}