using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

/// <summary>
    /// 导出Excel
    /// </summary>
    public class ExcelExport : IDisposable
    {
        int rowCount = 0;
        string sheetName = "sheet1";
        SpreadsheetDocument xl;
        OpenXmlWriter oxw;
        WorksheetPart wsp;
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="path">Excel文件名称(全路径)</param>
        /// <param name="rowCount">表格列数量</param>
        /// <param name="sheetName">表格名称</param>
        public ExcelExport(string path, int rowCount, string sheetName = "sheet1")
        {
            this.rowCount = rowCount;
            this.sheetName = sheetName ?? "sheet1";
            xl = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
            xl.AddWorkbookPart();
            wsp = xl.WorkbookPart.AddNewPart<WorksheetPart>();
            oxw = OpenXmlWriter.Create(wsp);
            oxw.WriteStartElement(new Worksheet());
            oxw.WriteStartElement(new SheetData());
        }
        /// <summary>
        /// 写入表格数据
        /// </summary>
        /// <param name="datas"></param>
        public void Write(object[] datas)
        {
            if (datas == null || datas.Length == 0) return;
            int colNum = datas.Length;
            //oxa = new List<OpenXmlAttribute>();
            // this is the row index
            //oxa.Add(new OpenXmlAttribute("r", null, i.ToString()));
            //oxw.WriteStartElement(new Row(), oxa);
            oxw.WriteStartElement(new Row());
            for (int j = 0; j < colNum; ++j)
            {
                var oxa = new List<OpenXmlAttribute>();
                // this is the data type ("t"), with CellValues.String ("str")
                oxa.Add(new OpenXmlAttribute("t", null, "str"));
                // it's suggested you also have the cell reference, but
                // you'll have to calculate the correct cell reference yourself.
                // Here's an example:
                //oxa.Add(new OpenXmlAttribute("r", null, "A1"));
                //c.Append(f);
                oxw.WriteStartElement(new Cell() { DataType = CellValues.InlineString }, oxa);
                //oxw.WriteStartElement(new Cell());
                oxw.WriteElement(new CellValue($"{datas[j]}"));
                // this is for Cell
                oxw.WriteEndElement();
            }
            // this is for Row
            oxw.WriteEndElement();
        }
        /// <summary>
        /// 写入表格数据
        /// </summary>
        /// <param name="datas"></param>
        public void Write(List<object> datas)
        {
            if (datas == null || datas.Count == 0) return;
            Write(datas.ToArray());
        }
        void Close()
        {
            // this is for SheetData
            oxw.WriteEndElement();
            // this is for Worksheet
            oxw.WriteEndElement();
            oxw.Close();
            oxw = OpenXmlWriter.Create(xl.WorkbookPart);
            oxw.WriteStartElement(new Workbook());
            oxw.WriteStartElement(new Sheets());
            // you can use object initialisers like this only when the properties
            // are actual properties. SDK classes sometimes have property-like properties
            // but are actually classes. For example, the Cell class has the CellValue
            // "property" but is actually a child class internally.
            // If the properties correspond to actual XML attributes, then you're fine.
            oxw.WriteElement(new Sheet()
            {
                Name = sheetName,
                SheetId = 1,
                Id = xl.WorkbookPart.GetIdOfPart(wsp)
            });
            // this is for Sheets
            oxw.WriteEndElement();
            // this is for Workbook
            oxw.WriteEndElement();
            oxw.Close();
            xl.Close();
        }
        #region IDisposable Support
        private bool disposedValue = false; // 要检测冗余调用
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                    Close();
                }
                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。
                disposedValue = true;
            }
        }
        // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
        // ~OpenXmlExt() {
        //   // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
        //   Dispose(false);
        // }
        // 添加此代码以正确实现可处置模式。
        void IDisposable.Dispose()
        {
            // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
            Dispose(true);
            // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
            // GC.SuppressFinalize(this);
        }
        #endregion
    }

使用:

object[] objTitle = new object[] { "SIM", "ICCID"};
string descFile="d:\\test.xlsx";
                using (var oxExt = new ExcelUtil.ExcelExport(descFile, objTitle.Length, "清单"))
                {
                    oxExt.Write(objTitle);

}

C# 基于DocumentFormat.OpenXml的数据导出到Excel的更多相关文章

  1. C# 基于Aspose.Cells的数据导出到Excel

    using Aspose.Cells;  void WriteToExcel(string filePath, List<object[]> datas, string sheetName ...

  2. 学习笔记 DataGridView数据导出为Excel

    DataGridView数据导出为Excel   怎样把WinForm下的“DGV”里的绑定数据库后的数据导出到Excel中. 比如:在窗体里有个一“DGV”,DataGridView1,绑定了数据源 ...

  3. 将C1Chart数据导出到Excel

    大多数情况下,当我们说将图表导出到Excel时,意思是将Chart当成图片导出到Excel中.如果是这样,你可以参考帮助文档中保存和导出C1Chart章节. 不过,也有另一种情况,当你想把图表中的数据 ...

  4. vb.net-三种将datagridview数据导出为excel文件的函数

    第一种方法较慢,但是数据格式都比较好,需要引用excel的 Microsoft.Office.Interop.Excel.dll  office.dll #Region "导出excel函数 ...

  5. 数据导出至Excel文件--好库编程网http://code1.okbase.net/codefile/SerializeHelper.cs_2012122018724_118.htm

    using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...

  6. 数据导出到Excel中

    自己修改后的一个数据导出到Excel的方法,粘出来与大家共享. 只需要将             System.Web.HttpContext.Current.Response.Charset =   ...

  7. asp.net将数据导出到excel

    本次应用datatable导出,若用gridview(假设gridview设为了分页显示)会出现只导出当前页的情况. protected void btnPrn_Click(object sender ...

  8. 将datagrid中数据导出到excel中 -------<<工作日志2014-6-6>>

    前台datagrid数据绑定 #region 导出到excel中    /// <summary>    /// 2014-6-6    /// </summary>    / ...

  9. 机房收费系统——在VB中将MSHFlexGrid控件中的数据导出到Excel

    机房收费系统中,好多查询的窗体都包含同一个功能:将数据库中查询到的数据显示在MSHFlexGrid控件中,然后再把MSHFlexGrid控件中的数据导出到Excel表格中. 虽然之前做过学生信息管理系 ...

随机推荐

  1. 网络层block,delegate之优劣分析

    正常情况下, block 缺点: 1.block很难追踪,难以维护 2.block会延长先关对象的生命周期 block会给内部所有的对象引用计数+1, 一方面会带来潜在的循环引用(retain cyc ...

  2. 最佳实践:腾讯HTAP数据库TBase助力某省核心IT架构升级

    https://mp.weixin.qq.com/s/56NHPyzx5F6QeCjuOq5IRQ 资源隔离能力: 在HTAP系统中,OLTP和OLAP业务要同时运行,两者都会消耗巨量的资源都,如果不 ...

  3. JS之JSON.parse和JSON.stringify

    这两个函数有兼容性问题, 会报错JSON"未定义 解决方案, 引入json2.js,可以解决浏览器的兼容性 https://link.jianshu.com/?t=https://githu ...

  4. 树形dp的深入讨论

    越发向dp深入越发现dp越有意思! 这道题做的时候感觉十分的难,然后看完学长的题解恍然大悟.设状态不好导致想了一中午,一直感觉不可做,其实是自己的状态设的不对,这道题呢,首先是一个求在树上建多个厂,而 ...

  5. C# decimal指定精度

    最近做一个项目.遇到了decimal 如何指定精度的问题 一般的指定参数    param = new SqlParameter(ParamName, DbType); 但decimal就不能只通过构 ...

  6. NOIP国王游戏

    #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #inc ...

  7. 八、自定义starter

    starter: 1.这个场景需要使用到的依赖是什么? 2.如何编写自动配置 @Configuration //指定这个类是一个配置类 @ConditionalOnXXX //在指定条件成立的情况下自 ...

  8. Docker 容器(六)

    镜像(Image)和容器(Container)的关系,就像是面向对象程序设计中的 类 和 实例 一样,镜像是静态的定义,容器是镜像运行时的实体.容器可以被创建.启动.停止.删除.暂停等. 容器的实质是 ...

  9. JSONObject,String,Map互相转换

    JSONObject和String相互转换 JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray( ...

  10. ionic 版本内更新问题汇总

    1.签名不一致导致的更新失败 2.解析软件包出现问题 3.当文件下载完.在android 8.0中不能打开apk包的问题 解决方案:在config.xml中添加: <platform name= ...