我可以移动合并的单元格来模拟EPPlus 3.1版本中的插入/删除列吗?我想移动单元格但在我尝试移动合并单元格时显示错误。
谢谢!
答案 0 :(得分:2)
由于没有人回应,我想我会告诉你我发现了什么。似乎在EPPlus 3.1或新版本4.0.1中无法做到这一点。我在源代码中创建了这个测试:
[TestMethod]
public void Move_Merged_Cells_Test()
{
//http://stackoverflow.com/questions/27230423/move-merged-cells-to-simulate-insert-and-delete-column
var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.Add("newsheet");
worksheet.Select("A1:C3");
worksheet.SelectedRange.Merge = true;
worksheet.SelectedRange.Value = "toto";
//worksheet.Select("A1");
worksheet.SelectedRange.Copy(worksheet.Cells["B1"]);
worksheet.SelectedRange.Clear();
package.Save();
}
}
最终在经过(从测试方法开始)workheet.SelectedRange.Copy(worksheet.Cells [“B1”])>之后点击方法。 .Clear()>删除(this)> DeleteCheckMergedCells(范围):
private void DeleteCheckMergedCells(ExcelAddressBase Range)
{
var removeItems = new List<string>();
foreach (var addr in Worksheet.MergedCells)
{
var addrCol = Range.Collide(new ExcelAddress(Range.WorkSheet, addr));
if (addrCol != eAddressCollition.No)
{
if (addrCol == eAddressCollition.Inside)
{
removeItems.Add(addr);
}
else
{
throw (new InvalidOperationException("Can't remove/overwrite cells that are merged"));
}
}
}
foreach (var item in removeItems)
{
Worksheet.MergedCells.Remove(item);
}
}
似乎它专门查找合并的单元格并抛出异常。我检查了4.0.1,这是同样的问题(他们重构了一些程序)。
所以似乎唯一的方法是取消合并,复制和重新合并。对不起,我无法给你一个更好的答案。
欧尼
答案 1 :(得分:1)
在清除之前需要取消合并。
worksheet.SelectedRange.Copy(worksheet.Cells["B1"]);
foreach (var cell in worksheet.SelectedRange) cell.Merge = false;
worksheet.SelectedRange.Clear();