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();
Web で見つけた例では、共有文字列テーブルについて言及されていませんでした。文字列データが出力されていないことに気付いたときに、そのことを知りました。
他に知っておくべき落とし穴はありますか?
コードに対するその他の批判はいつでも歓迎します。