Henehefu 用 ウィキ

メニュー



- Views

最近の更新

取得中です。

CSharp > OpenExcel > cs


※上記の広告は60日以上更新のないWIKIに表示されています。更新することで広告が下部へ移動します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
 
namespace OpenXmlExcelTest
{
    public class OpenExcel
    {
        public void Open(string path)
        {
            using(var excel = SpreadsheetDocument.Open(path, false))
            {
                // 頭がおかしくなって死ぬコード
                var shareStringPart = excel.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                var stringTable = shareStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
 
                Predicate<Cell> isTypeString = c => (c.DataType != null && c.DataType.Value == CellValues.SharedString);
                Func<Cell, string> getValue = c => c.CellValue.Text;
                Func<Cell, string> getString = c => stringTable[int.Parse(c.CellValue.Text)].InnerText;
                Func<Cell, string> getText = c => (isTypeString(c) ? getString : getValue)(c);
                Func<Cell, string> getPos = c => c.CellReference.Value;
 
                // Make
                var sheets = from s in excel.WorkbookPart.Workbook.Descendants<Sheet>()
                             let part = (WorksheetPart)excel.WorkbookPart.GetPartById(s.Id)
                             select new {
                                 Name = s.Name,
                                 Cells = from c in part.Worksheet.Descendants<Cell>()
                                         select new {
                                             Pos = getPos(c),
                                             Text = getText(c)
                                         }
                             };
                // Dump
                foreach(var sheet in sheets) {
                    Console.WriteLine(sheet.Name);
                    foreach(var cell in sheet.Cells) {
                        Console.WriteLine("{0}:{1}", cell.Pos, cell.Text);
                    }
                }
            }
        }
    }
}
 

タグ一覧