【发布时间】:2012-09-11 18:14:29
【问题描述】:
我需要从 xlsx 文件中提取文本(放入数据库的全文索引中)。 我正在使用以下代码:
using(SpreadsheetDocument d = SpreadsheetDocument.Open(stream, false)) {
// Load the shared strings table.
SharedStringTablePart stringTable =
d.WorkbookPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
if(stringTable == null) System.Diagnostics.Debug.WriteLine("Null string table");
foreach(WorksheetPart part in d.WorkbookPart.WorksheetParts) {
foreach(SheetData sheet in part.Worksheet.Elements<SheetData>()) {
bool added = false;
foreach(Row r in sheet.Elements<Row>()) {
foreach(Cell c in r.Elements<Cell>()) {
if(c.DataType != null) {
string v = c.CellValue.Text;
if(v != null && c.DataType.Value == CellValues.SharedString) {
var tableEntry = stringTable.SharedStringTable.ElementAt(int.Parse(v));
if(tableEntry != null) {
v = tableEntry.InnerText;
}
}
if(v != null) {
if(added) b.Append('\t');
b.Append(v);
added = true;
}
}
}
if(added) b.AppendLine();
}
}
}
}
return b.ToString();
我在网上找到的示例没有提到共享字符串表 - 当我意识到没有输出字符串数据时,我发现了它。
还有其他我应该知道的问题吗?
欢迎对代码提出其他批评。
【问题讨论】:
-
Other criticisms on the code always welcome.让 VS 缩进你的代码。 -
我做到了。然后我将标签更改为空格,以便在发布之前更容易阅读。
标签: c# openxml xlsx import-from-excel