我没有运气删除excel中的行,所以现在我尝试清除他们的内容并仍然得到错误: "无法删除/覆盖合并的单元格。范围部分与另一个合并范围合并。 A57788:J57788"
第1-10列真的已合并,但我如何取消合并?
这是我的代码:
cntr = 0;
while (ws.Cells[RowNum + cntr, 1].Value == null || !ws.Cells[RowNum + cntr, 1].Value.ToString().StartsWith("Report generation date"))
{
ws.Cells[RowNum + cntr, 1, RowNum + cntr, 18].Value = "";
ws.Cells[RowNum + cntr, 1, RowNum + cntr, 10].Merge = false;
for (int i = 1; i < 17; i++)
{
ws.Cells[RowNum + cntr, i].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.None);
ws.Cells[RowNum + cntr, i].Clear();
}
cntr++;
}
//ws.DeleteRow(RowNum, cntr);
答案 0 :(得分:1)
问题是你不能在一个范围内取消单个单元格,你必须取消整个范围。
为此,您可以使用我的解决方案here获取单元格所属的合并范围:
SELECT SUM(z_num)
FROM (SELECT z_num, rownum rown
FROM table)
WHERE rown < 10;
第二步是使用以下方法取消整个范围:
public string GetMergedRange(ExcelWorksheet worksheet, string cellAddress)
{
ExcelWorksheet.MergeCellsCollection mergedCells = worksheet.MergedCells;
foreach (var merged in mergedCells)
{
ExcelRange range = worksheet.Cells[merged];
ExcelCellAddress cell = new ExcelCellAddress(cellAddress);
if (range.Start.Row<=cell.Row && range.Start.Column <= cell.Column)
{
if (range.End.Row >= cell.Row && range.End.Column >= cell.Column)
{
return merged.ToString();
}
}
}
return "";
}
这种方式会让你失去其他单元格的合并及其价值,为了克服这个问题,你可以在清理和取消合并之前节省价值然后你可以把它写回来,比如:
public void DeleteCell(ExcelWorksheet worksheet, string cellAddress)
{
if (worksheet.Cells[cellAddress].Merge == true)
{
string range = GetMergedRange(worksheet, cellAddress); //get range of merged cells
worksheet.Cells[range].Merge = false; //unmerge range
worksheet.Cells[cellAddress].Clear(); //clear value
}
}