使用OpenXML时非常重要的一点是要检查您编写的代码与Office Excel的XML输出进行核对。
为了做到这一点,建议您安装
7Zip并提取.Xlsx文件,然后检查提取文件夹中的Xmls内容。
注意:一个Office文件包含多个XML文件,这些文件被打包为一个单独的.Xlsx文件。
然后进入Xl->Worksheet->Sheet1.xml
然后您可以看到这样一个XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
<dimension ref="A1:A4"/>
<sheetViews>
<sheetView tabSelected="1" workbookViewId="0">
<selection sqref="A1:A4"/>
</sheetView>
</sheetViews>
<sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25"/>
<sheetData>
<row r="1" spans="1:1" x14ac:dyDescent="0.25">
<c r="A1" s="1" t="s">
<v>0</v>
</c>
</row>
<row r="2" spans="1:1" x14ac:dyDescent="0.25">
<c r="A2" s="1"/>
</row>
<row r="3" spans="1:1" x14ac:dyDescent="0.25">
<c r="A3" s="1"/>
</row>
<row r="4" spans="1:1" x14ac:dyDescent="0.25">
<c r="A4" s="1"/>
</row>
</sheetData>
<mergeCells count="1">
<mergeCell ref="A1:A4"/>
</mergeCells>
<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
</worksheet>
在这个Excel文件中,我已经将
A1
到
A4
合并,并且你可以在XML末尾的
<mergeCells count="1">
中看到。此外,我在合并的单元格中写入了
Hello
。
因此,我认为要检查合并的单元格,你应该以某种方式使用。
在提取的文件夹中的
SharedString.xml
文件中,你可以看到:
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="1" uniqueCount="1"><si><t>Hello</t></si></sst>
您可以看到count
属性的值等于<mergeCells />
标签的count
值。
这些是介绍,告诉您OpenXml只是一个适当的库,它只解析XML。
如果您查看我通过阅读XML文件编写的下面的代码,并注意变量名称,您将看到我只是尝试浏览XML标记并找到我的适当值。
using (SpreadsheetDocument document = SpreadsheetDocument.Open(@"D:\test.xlsx", true))
{
WorkbookPart wbPart = document.WorkbookPart;
List<WorksheetPart> wsParts = wbPart.WorksheetParts.ToList();
if (wsParts != null && wsParts.Any())
{
WorksheetPart SheetPart1 = wsParts.First();
MergeCells mergeCells = SheetPart1.Worksheet.Elements<MergeCells>().First();
foreach (MergeCell mergeCell in mergeCells)
{
string[] mergedRow = mergeCell.Reference.Value.Split(new string[]{":"},StringSplitOptions.None);
Cell theCell = SheetPart1.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == mergedRow[0]).FirstOrDefault();
string value = GetCellValue(document, theCell);
}
}
}
然后:
。
public string GetCellValue(SpreadsheetDocument document, Cell cell)
{
SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
string value = string.Empty;
if (cell.CellValue != null)
{
value = cell.CellValue.InnerXml;
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
}
}
return value;
}