在excel文件中包含数据,如下所示,其中第1行和第1行2被视为标题行,当根据第一列拆分此特定文件时,将对其进行复制。
分割后的文件如下所示:
问题是在这种情况下,将列D的值复制到错误的C列。
我认为我需要检查单元格是空还是空,并在写入期间将空/空值放入新文件。问题是如何将其纳入我的以下代码?
private FileEntity GetFileObject(Excel.Range range)
{
FileEntity fileEntity = new FileEntity();
fileEntity.RowValues = new List<RowEntity>();
for (int rowCount = 1; rowCount <= range.Rows.Count; rowCount++)
{
RowEntity rowEntity = new RowEntity();
rowEntity.ColumnValues = new List<string>();
for (int columnCount = 1; columnCount <= range.Columns.Count; columnCount++)
{
if ((range.Cells[rowCount, columnCount] as Excel.Range).Value != null)
{
rowEntity.ColumnValues.Add((range.Cells[rowCount, columnCount] as Excel.Range).Value.ToString());
}
}
fileEntity.RowValues.Add(rowEntity);
}
return fileEntity;
}
答案 0 :(得分:0)
这是因为文档结构具有内置的效率,可以避免浪费空间。您必须检查单元格以供参考(A1,B1等),然后您就可以知道它来自何处以及如何处理它。
int rowIdx = 0;
foreach (Row r in sheetData.Elements<Row>().Skip(1))
{
rowIdx++;
IEnumerable<Cell> thisRow = r.Elements<Cell>();
foreach (var c in thisRow)
{
//This will tell you what cell you are looking at (A2, D14, whatever..)
string cellRef = c.CellReference.ToString().Substring(0, 1);
switch (cellRef)
{
case "A":
//do something...
break;
case "B":
//do something...
break;
case "C":
//do something...
break;
....ETC.......
答案 1 :(得分:0)
找到解决方案:
if ((range.Cells[rowCount, columnCount] as Excel.Range).Value != null)
{
rowEntity.ColumnValues.Add((range.Cells[rowCount, columnCount] as Excel.Range).Value.ToString());
}
else
rowEntity.ColumnValues.Add(""); //just add this line. keeps the blank cell as created with empty string