读写.docx和.xlsx文档的C#类 - Simple OOXML

Simple OOXML 是 CodePlex 上的一个开源项目,使用Open Xml SDK 2.0 ,封装了一系列读写.docx和.xlsx文档的类,可以很大程度上简化工作。
它提供以下这些类:
  • SpreadsheetReader - manipulation of templates, retrieval of document parts, row and column reference functionality
  • SpreadsheetWriter - writing of document parts and creation of document level attributes. Add or remove spreadsheets.
  • SpreadsheetStyle - encapsulates font, border and fill handing in a spreadsheet.
  • WoksheetReader - retrieves cell and style information from a worksheet
  • WorksheetWriter - allows the pasting or insertion of data and style - using simple value types or DataTables - at a cell or range reference.
  • DocumentReader - retrieval of document templates.
  • DocumentWriter - pastes and saves text and text lists using predefined bookmarks.

示例代码:

using (var stream = SpreadsheetReader.StreamFromFile("test.xlsx"))
{
    using (var doc = SpreadsheetDocument.Open(stream, true))
    {
        var sheet = SpreadsheetReader.GetWorksheetPartByName(doc, "Sheet1");
        var writer = new WorksheetWriter(doc, sheet);
 
        //获取默认样式
        var style1 = SpreadsheetStyle.GetDefault(doc);
        style1.SetBackgroundColor("97DDFF");//设置背景颜色
        style1.SetHorizontalAlignment(HorizontalAlignmentValues.Center);//设置水平居中对齐
        style1.SetBorder("000000", BorderStyleValues.Thin);//设置边框
        var data = new[] {
            new {Name = "小郑",Sex = "男",Age = 20},
            new {Name = "小王",Sex = "女",Age = 19}
        };
 
        int rowIndex = 2;
        for (int i = 0; i < data.Length; i++)
        {
            writer.PasteText("A" + rowIndex, data[i].Name, style1);//写入姓名
            writer.PasteText("B" + rowIndex, data[i].Sex, style1);//写入性别
            writer.PasteNumber("C" + rowIndex, data[i].Age.ToString(), style1);//写入年龄
            rowIndex++;
        }
        writer.Save();//在内存中保存文档结构
        SpreadsheetWriter.StreamToFile("test.xlsx", stream);//保存到文件中
    }
}



你可能感兴趣的:(Excel,C#,simple,OOXML)