使用 OpenXml 将日语字符串写入 excel

Writing Japanese string to excel using OpenXml

我正在尝试通过从数据库中读取数据来创建 Excel 文件。其中一列包含日语文本。将该列写入 excel 单元格并保存工作簿时会出现以下错误(这是有道理的,因为字符无效 xml 字符):'',十六进制值 0x0B,无效字符.

我正在使用 DocumentFormat.OpenXml 包将如下字符串写入 excel 单元格。

var excelCell = new Cell();
var cellValue = dtRow[col.Name].ToString(); 
var inlineStr = new InlineString(new Text(cellValue));
excelCell.DataType = CellValues.InlineString;
excelCell.InlineString = inlineStr;

在 C# 中使用 OpenXml 将日语字符写入 excel 需要做什么

好的。找到了正确的方法。把它作为答案,这样它会有所帮助。 要将不允许作为有效 xml 的文本添加到 excel,请将文本作为 SharedString 添加到 SharedStringTable

var index = InsertSharedStringItem(text, shareStringPart);
excelCell.CellValue = new CellValue(index.ToString());
excelCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);



        private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
        {
            // If the part does not contain a SharedStringTable, create one.
            if (shareStringPart.SharedStringTable == null)
            {
                shareStringPart.SharedStringTable = new SharedStringTable();
            }

            int i = 0;

            // Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
            foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
            {
                if (item.InnerText == text)
                {
                    return i;
                }

                i++;
            }

            // The text does not exist in the part. Create the SharedStringItem and return its index.
            shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));
            shareStringPart.SharedStringTable.Save();

            return i;
        }

使用 OpenXml 将文本作为共享字符串添加到 excel 的完整文档 https://msdn.microsoft.com/en-us/library/office/cc861607.aspx