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. 再探树形dp

    随着校oj终于刷进了第一页,可以不用去写那些水题了,开始认真学习自己的东西,当然包括文化课.努力.. 这道题呢是道树形dp,可看到了根本就不知道怎么写思考过程: 5min 终于看懂了题 画了样例的图把 ...

  2. 查找->动态查找表->平衡二叉树

    文字描述 平衡二叉树(Balanced Binary Tree或Height-Balanced Tree) 因为是俄罗斯数学家G.M.Adel’son-Vel’skii和E.M.Landis在1962 ...

  3. LeetCode 104 Maximum Depth of Binary Tree 解题报告

    题目要求 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the ...

  4. MonkeyRunner_手机触摸屏幕坐标获取

    坐标单位为像素,获取方式包括手机自带.画图软件和photoshop软件. 方式一.android4.0以上系统手机自带坐标功能,在设置->开发者选项->显示指针位置 方式二.画图或phot ...

  5. Java线程的状态分析

    线程状态 1.新建状态(New):新创建了一个线程对象. 2.就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法.该状态的线程位于“可运行线程池”中,变得可运行,只 ...

  6. eclipse debug调试时老是被URLClassLoader这个类拦截到,不能进入到要调试的类里面去

    在使用eclipse进行试的时候,一直进入到URLClassLoader,而不能正常的进入断点,后来经过查资料,解决方法如下: 上面是百度给出的答案,我把图贴在这里,以便以后其他组的朋友遇到这个问题的 ...

  7. 关于WARN Dispatcher:68 - Could not find action or result报错

    出现这个错 00:03:37,142 WARN Dispatcher:68 - Could not find action or result: /crm/linkMan_addLinkMan.act ...

  8. LeetCode-52.N-Queen II

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens ...

  9. mysql连接池不能回避的wait timeout问题(转)

    起因 我们的项目组一直在使用albianj作为开发框架在开发应用.使用至今倒也是没有出现很大的问题,但最近加过监控的接口基本上都会在使用一段时间后,突然之间执行数据库操作变得很慢.虽然会变慢,但持续的 ...

  10. 【分类器】感知机+线性回归+逻辑斯蒂回归+softmax回归

    一.感知机     详细参考:https://blog.csdn.net/wodeai1235/article/details/54755735 1.模型和图像: 2.数学定义推导和优化: 3.流程 ...