Simple OOXML 是 CodePlex 上的一个开源项目,使用Open Xml SDK 2.0 ,封装了一系列读写.docx和.xlsx文档的类,可以很大程度上简化工作。
示例代码:
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);//保存到文件中 } }