使用 Interop c# 将数据写入 Excel

问题描述 投票:0回答:1

我可以借助.Net Core中的Interop将数据写入excel,但是有什么方法可以不改变现有的excel模板。

实际上我有一个 Excel 模板,对于多个用户,我想要不同的 Excel 数据,但我的代码正在将数据写入我的主文件,这是我不想要的。

请帮我解决这个问题。

我使用了以下代码来编写:

using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
//Microsoft Excel 16 object in references-> COM tab
using Excel = Microsoft.Office.Interop.Excel;

Application xlApp = new Application();
float Left;
float Top;
string FilePath = DefaultImagesPath;

Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
_Worksheet xlWorksheet = (_Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

xlWorksheet.Cells[5, 5] = "text";

//For Image
Excel.Range primaryOkImageRange = (Excel.Range)xlWorksheet.Cells[20, 15];
Left = (float)((double)primaryOkImageRange.Left);
Top = (float)((double)primaryOkImageRange.Top);
xlWorksheet.Shapes.AddPicture(FilePath, MsoTriState.msoFalse, MsoTriState.msoCTrue, 
Left, Top, 50, 50);

xlApp.Visible = false;
xlApp.UserControl = false;

//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//close and release
xlWorkbook.Close();
//quit and release
xlApp.Quit();

我试图清除现有值:

var rng = (Excel.Range)xlWorksheet.Cells[5, 5];
Left = (float)((double)rng.Left);
Top = (float)((double)rng.Top);
rng.Cells.Clear();

但这不起作用。

c# interop excel-interop
1个回答
0
投票

嗨,我要感谢 JonasH 提供的想法。刚刚做了以下更改,我的场景现在成功了。

 if (File.Exists(DestinationFileName))
 {
 File.Delete(DestinationFileName);
 }

 File.Copy(SourceFileName, DestinationFileName, true);
 Workbook xlWorkbook = xlApp.Workbooks.Open(DestinationFileName);
© www.soinside.com 2019 - 2024. All rights reserved.