简体   繁体   English

C#Excel生成-使用最后一个单元格作为正确数据的第一个单元格进行范围复制(不良行为)

[英]C# Excel Generation - Range Copy (undesired behavior) using last cell as first cell of correct data

List<someClass> aList = new List<someClass>();

...

XLWorkbook workbook = new XLWorkbook();
IXLWorksheet worksheet = workbook.AddWorksheet("Data");
worksheet.Hide();
workbook.CalculateMode = XLCalculateMode.Manual;

var data = aList.ToArray();
var firstCell = worksheet.Cell(1, 1);
var lastCell = worksheet.Cell(numRows, numColumns); // numRows = 150, numColumns = 8
var writeRange = worksheet.Range(firstCell, lastCell); //firstCell = A1, LastCell = H150
writeRange.Value = data;

workbook.SaveAs(mySavePath);

This bit of code is meant to copy the data in aList into a new excel document, only, instead of starting at cell A1(1,1) and ending at cell H150 it copies the value from cell 1 into all of the cells between A1 and H299, the row values that should be in row 1 into column HO from row 1-150, and finally my correctly grouped data from H150-O299. 这部分代码仅用于将aList中的数据复制到新的excel文档中,而不是从单元格A1(1,1)开始到单元格H150结束,而是将值从单元格1复制到A1之间的所有单元格中和H299,应该是从1-150行到HO列的第1行中的行值,最后是H150-O299中正确分组的数据。

Basically, my data starts at the offset of the range instead of filling in the range, and everything above and left of that range is default copied (garbage) data. 基本上,我的数据从该范围的偏移量开始,而不是填充该范围,并且该范围上下的所有内容都是默认复制(垃圾)数据。 someClass is just a public class with public fields for ints and strings. someClass只是一个公共类,其中包含用于整数和字符串的公共字段。

Can anyone tell me why this is happening and how I can correct it? 谁能告诉我为什么会这样以及如何纠正呢?

As a solution, I found that using the same index for first and last cell will properly input my data, however why Range does not work as (assumed) intended has yet to be answered. 作为解决方案,我发现在第一个和最后一个单元格中使用相同的索引将正确输入我的数据,但是为什么Range不能按预期的方式工作仍未得到解答。

var firstCell = worksheet.Cell(1, 1);
var writeRange = worksheet.Range(firstCell, firstCell); //firstCell = A1, LastCell = H150

This will work as intended. 这将按预期工作。 I've completely removed lastCell as it is unnecessary. 由于不必要,我已经完全删除了lastCell。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM