ASP.NET Simple OOXML导出Excel,Word

来源:http://www.cnblogs.com/zrx401558287/archive/2012/07/05/2577904.html

 

1)简介

  Simple OOXML(http://simpleooxml.codeplex.com/)是一个基于Open Office SDK v 2.0,同时支持office2007 Excel和Word导出的开源类库。支持.net 3.5及以上版本。对于Excel支持多种数据格式包括字符串、数字、日期等,支持删除工作簿,支持DataTable的粘贴,支持合并单元格和设置单元格样式等等。对于Word支持通过书签定位来输出字段的功能。

  下载地址:本地下载

2)导出Excel

复制代码
        protected void Button1_Click(object sender, EventArgs e)
        {
            MemoryStream stream = SpreadsheetReader.Create();
            SpreadsheetDocument doc = SpreadsheetDocument.Open(stream, true);
            WorksheetPart worksheetPart = SpreadsheetReader.GetWorksheetPartByName(doc, "Sheet1");
            WorksheetWriter writer = new WorksheetWriter(doc, worksheetPart);

            writer.PasteText("B2", "Hello World");
            

            //Save to the memory stream
            SpreadsheetWriter.Save(doc);
            
            //Write to response stream
            Response.Clear();
            Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "example1.xlsx"));
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            stream.WriteTo(Response.OutputStream);
            Response.End();
        }
复制代码

  如果是现有Excel模版的导出则可以把

MemoryStream stream = SpreadsheetReader.Create();

  修改为

MemoryStream stream = SpreadsheetReader.Copy(“columnstemplate.xlsx");

3)导出Word

复制代码
        public void DocumentPasteTest()
        {
            MemoryStream stream = DocumentReader.Copy(string.Format("{0}\\template.docx", TestContext.TestDeploymentDir));
            WordprocessingDocument doc = WordprocessingDocument.Open(stream, true);
            
            MainDocumentPart mainPart = doc.MainDocumentPart;

            DocumentWriter writer = new DocumentWriter(mainPart);
            
            Text name = writer.PasteText("Koos van der Merwe", "NAME");
            Text age = writer.PasteText("53", "AGE");
            //Save to the memory stream, and then to a file
            writer.Save();

            DocumentWriter.StreamToFile(string.Format("{0}\\templatetest.docx", GetOutputFolder()), stream);

        }
复制代码

  通过Word的书签功能实现粘贴文本的定位。

4)结语

  Simple OOXML是一个功能非常全面好用的导出Excel和Word的解决方案,唯一美工不足是不支持office 2003的导出,希望对于.NET导出数据的朋友有所帮助。

posted @ 2012-07-05 15:39  冰封的心  阅读(485)  评论(0编辑  收藏  举报