读写.docx和.xlsx文档的C#类 - Simple OOXML
fmms
13年前
Simple OOXML 是 CodePlex 上的一个开源项目,使用Open Xml SDK 2.0 ,封装了一系列读写.docx和.xlsx文档的类,可以很大程度上简化工作。 <br /> 它提供以下这些类: <ul> <li>SpreadsheetReader - manipulation of templates, retrieval of document parts, row and column reference functionality</li> <li>SpreadsheetWriter - writing of document parts and creation of document level attributes. Add or remove spreadsheets.</li> <li>SpreadsheetStyle - encapsulates font, border and fill handing in a spreadsheet.</li> <li>WoksheetReader - retrieves cell and style information from a worksheet</li> <li>WorksheetWriter - allows the pasting or insertion of data and style - using simple value types or DataTables - at a cell or range reference.</li> <li>DocumentReader - retrieval of document templates.</li> <li>DocumentWriter - pastes and saves text and text lists using predefined bookmarks.</li> </ul> <br /> 示例代码: <pre class="brush:c#; toolbar: true; auto-links: false;">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);//保存到文件中 } }</pre> <p><strong>项目主页:</strong><a href="http://www.open-open.com/lib/view/home/1326936587577" target="_blank">http://www.open-open.com/lib/view/home/1326936587577</a></p>