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. angular ajax请求 结果显示显示两次的问题

    angular 项目中,由于用到ajax 请求,结果显示如下情况 同样的接口,显示两次,其中第一次请求情况为 request method 显示为opttions 第二次的情况是 为啥会出现如此的情况 ...

  2. Mysql thread 与 OS thread

    测试环境信息如下: OS:Ubuntu 16.04 LTS Mysql:Mysql 5.7.18,使用docker images运行的实例 Mysql如何处理client请求 在Mysql中,连接管理 ...

  3. xcode工程编译错误:error: Couldn’t materialize

    错误信息: error: Couldn't materialize: couldn't get the value of variable amount: variable not available ...

  4. =[Mathematics] 数学主题

    https://www.douban.com/group/maths/ 圆锥体体积公式的证明

  5. 玩具装箱&土地购买

    今天一天8h 写了两道斜率优化的题(别问我效率为什么这么低 代码bug太多了) 关键是思考的不周全 估计是写的题少手生 以后就会熟练起来了吧. 这道题显然有一个n^2的dp方程 设f[i]表示前i件物 ...

  6. LeetCode 832 Flipping an Image 解题报告

    题目要求 Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the ...

  7. Qt网络模块如何使用(表格)

    1.网络模块介绍 类名 说明 中文 QAbstractNetworkCache The interface for cache implementations 缓存实现的接口 QNetworkCach ...

  8. SQL Server 无法连接数据库

    1.打开SQL server 配置管理器-->SQL server 网络配置-->实例名的协议 2.保证SQLEXPRESS协议中的Named Pipes和 TCP/IP启用. 3.点击S ...

  9. zabbix agentd安装

    一.Linux客户端1.创建zabbix用户 groupadd zabbix useradd -g zabbix -M -s /sbin/nologin zabbix 2.解压agent包 zabbi ...

  10. [MySQL 5.6] information_schema.innodb_metrics

    1. 概括 已关闭/打开的配置 use information_schema select count(*), status from innodb_metrics group by status; ...