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. Vue SSR 配合Java的Javascript引擎j2v8实现服务端渲染2创建Vue2+webpack4项目

    前提 安装好nodejs并配置好环境变量,最好是 node10,https://nodejs.org/en/download/ 参考我之前的文章 debian安装nodejs Yarn &&a ...

  2. RabbitMQ的Vhost,Exchange,Queue原理分析

    Vhost分析 RabbitMQ的Vhost主要是用来划分不同业务模块.不同业务模块之间没有信息交互. Vhost之间相互完全隔离,不同Vhost之间无法共享Exchange和Queue.因此Vhos ...

  3. day11:装饰器

    1,引子,计算函数的运行时间: import time def func(): time.sleep(0.01) # 为了计算运行时间差的时候有值 print("func") de ...

  4. 在SVNX中实现$Ids的自动替换

    在PHPstorm中实现$Ids的自动替换 ①.打开SVN的配置文件. [miscellany] enable-auto-props = yes [auto-props] .c = svn:keywo ...

  5. tst

    select count(*) from student where age>18 group by 性别 having count(*)>2 order by age where过滤的是 ...

  6. 20165225《Java程序设计》第九周学习总结

    20165225<Java程序设计>第九周学习总结 1.视频与课本中的学习: 第十三章学习总结 URL类 URL对象包含三部分信息:协议.地址和资源 创建URL对象两种方法: public ...

  7. 浏览器数据库 IndexedDB 入门教程

    一.概述 随着浏览器的功能不断增强,越来越多的网站开始考虑,将大量数据储存在客户端,这样可以减少从服务器获取数据,直接从本地获取数据. 现有的浏览器数据储存方案,都不适合储存大量数据:Cookie 的 ...

  8. es6 学习四 数组的学习

    1. Array.from() 语法: Array.from(arrayLike[, mapFn[, thisArg]]) arrayLike 类数组对象 mapFn 如果指定了该参数,新数组中的每个 ...

  9. Maven中groupId和artifactId的含义

    groupId和artifactId被统称为“坐标”是为了保证项目唯一性而提出的,如果你要把你项目弄到maven仓库去,你想要找到你的项目就必须根据这两个id去查找.groupId是项目组织唯一的标识 ...

  10. Linux 抓包工具:tcpdump

    tcpdump 是一个抓包工具,通常用来分析网络 安装tcpdump命令 [root@mysql test]# yum install -y tcpdump -i 指定网卡 捉取网卡数据包 抓取指定网 ...