我有生成格式化 Excel 报告的 ac# 程序。由于 Office 的升级,我将程序转换为使用 Microsoft Excel 16 对象库。一切都很好,除了 pagesetup 类。新 DLL 不再支持 Pagesetup 类。由于报告的代码很长,我决定最后用 OpenXML 修改 Excel 文件。
我通过将文件的后缀更改为 zip 来研究原始 OpenXML。下面是对应于 pagesetup 类的原始 OpenXML。
<printOptions horizontalCentered="1"/>
<pageMargins left="0.5" right="0.5" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
<pageSetup orientation="landscape" r:id="rId1"/>
<headerFooter><oddHeader>&L&"Arial Narrow,Bold"&8 9825 Fairmount Drive SE
&R&"Arial Narrow,Bold"&8Ref. No.: 10-219</oddHeader>
<oddFooter>&C&"Arial Narrow,Regular"&8Page 1 of 2</oddFooter></headerFooter>
<headerFooter>
<oddHeader>&R&8&B&"Arial Narrow"Ref. No.: 10-219
&L&8&B&"Arial Narrow"9825 Fairmount Drive SE</oddHeader>
<oddFooter>&C&8&"Arial Narrow"Page 2 of 2</oddFooter></headerFooter>
但是,在我使用 OpenXML 函数格式化 Excel 文件后,Excel 告诉我文件中存在 OpenXML 代码错误。以下是从修改后的文件中提取的内容:
<x:pageMargins left="0.5" right="0.5" top="0.75" bottom="0.75" header="0.3" footer="0.3" />
<x:printOptions horizontalCentered="1" />
<x:pageSetup orientation="landscape" />
<x:headerFooter differentOddEven="0">
<x:oddHeader>&L&B&"Arial Narrow"&9825 Fairmount Drive SE&R&B&"Arial Narrow"&8Ref. No.: 10-219</x:oddHeader>
<x:oddFooter>&C&"Arial Narrow"&8Page &P of &N</x:oddFooter></x:headerFooter>
它似乎在每个标签的开头放置了一个 x: 和 /x:。下面是我的 OpenXML 函数。
public void formatLandscapeReport(String fileName, String jobNumber, String Address) {
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, true))
{
WorkbookPart workbookpart = document.WorkbookPart;
IEnumerable<String> worksheetIds = workbookpart.Workbook.Descendants<Sheet>().Select(w => w.Id.Value);
WorksheetPart worksheetpart = null;
foreach (String worksheetId in worksheetIds)
{
worksheetpart = ((WorksheetPart)workbookpart.GetPartById(worksheetId));
PrintOptions po = new PrintOptions();
po.HorizontalCentered = true;
worksheetpart.Worksheet.AppendChild(po);
PageMargins pm = worksheetpart.Worksheet.Descendants<PageMargins>().FirstOrDefault();
if (pm == null)
{
pm = new PageMargins();
worksheetpart.Worksheet.AppendChild(pm);
}
pm.Left = .5D;
pm.Right = .5D;
pm.Top = .75D;
pm.Bottom = .75D;
PageSetup pagesetup = worksheetpart.Worksheet.Descendants<PageSetup>().FirstOrDefault();
if (pagesetup == null)
{
pagesetup = new PageSetup();
worksheetpart.Worksheet.AppendChild(pagesetup);
}
pagesetup.Orientation = OrientationValues.Landscape;
// Header and Footer
HeaderFooter hf = new HeaderFooter();
hf.DifferentOddEven = false;
OddHeader ohdr = new OddHeader();
OddFooter oftr = new OddFooter();
ohdr.Text= "&L&B&\"Arial Narrow\"&" + Address +"&R&B&\"Arial Narrow\"&8Ref. No.: " + jobNumber;
oftr.Text = "&C&\"Arial Narrow\"&8Page &P of &N";
hf.Append(ohdr);
hf.Append(oftr);
worksheetpart.Worksheet.Append(hf);
worksheetpart.Worksheet.Save();
} // foreach
workbookpart.Workbook.Save();
} // using
} //formatLandscapeReport
如果有人能告诉我我做错了什么,将不胜感激。
谢谢,
卡门