简体   繁体   English

OpenXml - 读取 Excel 文件时保留撇号

[英]OpenXml - Preserve apostrophe when reading Excel file

I'm trying to read an Excel file which looks like this:我正在尝试读取一个如下所示的 Excel 文件:

Excel文件

...reading the file using this example https://stackoverflow.com/a/26063965/281451 ...使用此示例读取文件https://stackoverflow.com/a/26063965/281451

But when I try to print the content of the cells, it's missing the leading apostrophes and it prints something like this:但是当我尝试打印单元格的内容时,它缺少前导撇号,它打印出如下内容:

cell val: 10000001

instead of what I'm expecting:而不是我所期待的:

cell val: '10000001

Is there anyway of achieving this?有没有办法做到这一点?

The leading apostrophe is not considered to be a part of a cell's value.前导撇号不被视为单元格值的一部分。 This is more the convention that Excel uses to have some text instead of a number.这更多是 Excel 用来包含一些文本而不是数字的约定。

To give you an example, let's say you want to write 0001 in some cell, if you write it like that MS Excel will parse it as a number and set the cell to number 1.举个例子,假设您想在某个单元格中写入 0001,如果您这样写,MS Excel 会将其解析为数字并将单元格设置为数字 1。
However, if you write that text with leading apostrophe then MS Excel will leave it as it is.但是,如果您使用前导撇号编写该文本,则 MS Excel 将保持原样。

Anyway, here is how you can detect if you should add that leading apostrophe:无论如何,您可以通过以下方法检测是否应该添加前导撇号:

var document = SpreadsheetDocument.Open(filePath, false);
var sharedStringTable = document.WorkbookPart.SharedStringTablePart.SharedStringTable;

var cellFormats = document.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats;

// ...

if (cell.DataType == CellValues.SharedString)
{
    bool isQuoted = false;
    if (cell.StyleIndex != null && cell.StyleIndex.HasValue)
    {
        var cellFormat = cellFormats.ChildElements[(int)cell.StyleIndex.Value] as CellFormat;
        isQuoted = cellFormat.QuotePrefix;
    }

    Console.WriteLine("cell val: " + (isQuoted ? "'" : "") + sharedStringTable.ElementAt(Int32.Parse(cellValue)).InnerText);
}

// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM