如何通过Open XML生成单元格格式为Text的Excel文件?
解决Open XML导出Excel单元格设置为Text格式问题
要将导出的Excel单元格格式设置为Text而非默认的General,仅设置单元格值为字符串或使用默认style index 0是无效的,需要通过自定义单元格样式来实现,具体步骤如下:
1. 添加自定义文本格式到样式部分
在创建SpreadsheetDocument后,先在WorkbookStylesPart中定义文本格式:
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; // 假设已创建SpreadsheetDocument实例document var stylesPart = document.WorkbookPart.AddNewPart<WorkbookStylesPart>(); stylesPart.Stylesheet = new Stylesheet(); // 定义文本格式(格式代码"@"对应Text类型) var numberingFormats = new NumberingFormats(); var textNumberingFormat = new NumberingFormat { NumberFormatId = UInt32Value.FromUInt32(164), // 自定义格式ID从164开始(0-163为内置格式) FormatCode = StringValue.FromString("@") }; numberingFormats.Append(textNumberingFormat); stylesPart.Stylesheet.Append(numberingFormats); // 添加默认的字体、填充、边框(使用内置默认样式) stylesPart.Stylesheet.Append( new Fonts(new Font()), new Fills(new Fill()), new Borders(new Border()) ); // 创建单元格格式集合,关联文本格式 var cellFormats = new CellFormats(); // 保留默认General格式(index 0) cellFormats.Append(new CellFormat { NumberFormatId = 0, FontId = 0, FillId = 0, BorderId = 0 }); // 添加自定义文本格式(index 1) cellFormats.Append(new CellFormat { NumberFormatId = 164, FontId = 0, FillId = 0, BorderId = 0, ApplyNumberFormat = BooleanValue.FromBoolean(true) // 启用格式应用 }); stylesPart.Stylesheet.Append(cellFormats); stylesPart.Stylesheet.Save();
2. 创建单元格时指定文本样式
在生成单元格时,设置StyleIndex为自定义文本格式的索引(即1),同时指定数据类型为字符串:
// 创建单元格示例 var cell = new Cell { CellReference = "A1", DataType = CellValues.String, CellValue = new CellValue("需要以文本格式显示的内容"), StyleIndex = UInt32Value.FromUInt32(1) // 使用自定义的文本样式 };
关键说明
- 内置格式ID(0-163)中没有直接可复用的Text格式,必须自定义格式ID(从164开始)并指定格式代码
@。 - 设置
ApplyNumberFormat = true是确保格式生效的关键,否则即使关联了数字格式也不会应用。
内容的提问来源于stack exchange,提问作者CSharp User
相关产品推荐
相关产品推荐

