![](/img/trans.png)
[英]How can I get the specific column in excel worksheet using DocumentFormat.OpenXml C#?
[英]How to get a merged cell from Excel using DocumentFormat.OpenXML or ClosedXML C#
我需要仅使用 DocumentFormat.OpenXml 或 ClosedXML 获取合并单元格的区域,该区域以 Excel 结尾的行号,如何为每个单元格执行此操作?
我发现这有点笨拙,但我相信这是正确的方法。
private static void GetMergedCells()
{
var fileName = $"c:\\temp\\Data.xlsm";
// Open the document for editing.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// Get the WorkbookPart object.
var workbookPart = document.WorkbookPart;
// Get the first worksheet in the document. You can change this as need be.
var worksheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();
// Retrieve the WorksheetPart using the Part ID from the previous "Sheet" object.
var worksheetPart = (WorksheetPart)workbookPart.GetPartById(worksheet.Id);
// Retrieve the MergeCells element, this will contain all MergeCell elements.
var mergeCellsList = worksheetPart.Worksheet.Elements<MergeCells>();
// Now loop through and spit out each range reference for the merged cells.
// You'll need to process the range either as a string or turn it into another
// object that gives you the end row.
foreach (var mergeCells in mergeCellsList)
{
foreach (MergeCell mergeCell in mergeCells)
{
Console.WriteLine(mergeCell.Reference);
}
}
}
}
如果你还不能说,这是使用DocumentFormat.OpenXml.Spreadsheet
使用 ClosedXML,这可以通过以下方式完成:
var ws = workbook.Worksheet("Sheet 1");
var cell = ws.Cell("A2");
var mergedRange = cell.MergedRange();
var lastCell = mergedRange.LastCell();
// or
var lastCellAddress = mergedRange.RangeAddress.LastAddress;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.