gpt4 book ai didi

C# 打开 Excel 模板,复制行格式并将新数据插入每个新行

转载 作者:行者123 更新时间:2023-12-04 22:32:16 25 4
gpt4 key购买 nike

我希望遍历文件夹中的所有文件并将它们的文件名添加到 Excel 中的一行中。为此,我有一个我希望使用的模板 Excel 文件,并开始在包含公式的特定行添加数据。

我使用下面的数据,我能够遍历文件,但我无法复制该行并在粘贴数据之前插入另一个行,因为我收到错误

    string rootfolder = Path.GetDirectoryName(path);
string folder = Path.GetFileName(Path.GetDirectoryName(path));

var excelApp = new Application();
var workbook = excelApp.Workbooks.Open(fileName);
var mWorkSheets = workbook.Worksheets;
var worksheet = (Worksheet)mWorkSheets.get_Item("Invoice");

excelApp.Visible = true;

int x = 13; // <- The row to copy which has formulas
Range RngToCopy = worksheet.get_Range("b13" , "l13").EntireRow;
foreach (var item in files)
{

Range RngToInsert = worksheet.get_Range("b" + x, Type.Missing).EntireRow;
RngToInsert.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, RngToInsert.Copy(Type.Missing)); // --< Throws the error

worksheet.Cells[x, 2].Value2 = item.date;
worksheet.Cells[x, 3].Value2 = item.reference;
worksheet.Cells[x, 4].Value2 = item.source;
worksheet.Cells[x, 5].Value2 = item.count;
worksheet.Cells[x, 6].Value2 = item.costPerWord;
worksheet.Cells[x, 7].Value2 = item.STBY;
worksheet.Cells[x, 8].Value2 = item.costSTBY;
worksheet.Cells[x, 9].Value2 = item.SCH;
worksheet.Cells[x, 10].Value2 = item.costSCH;

x++;
}

错误

//System.Runtime.InteropServices.COMException: 'This won't work because it would move cells in a table on your worksheet.'

最佳答案

我想这取决于你的模板。
当您尝试在 Excel 中编辑格式化表或链接表(例如 odbc)时,会出现错误消息。
你能用一张空白的excel表试试你的代码,看看这是否有效,如果是这样,那是你的模板本身的问题,而不是代码的问题。

代码本身看起来不错

关于C# 打开 Excel 模板,复制行格式并将新数据插入每个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51802678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com