Csharp: read excel file using Open XML SDK 2.5

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Spreadsheet;

namespace OpenXmlOficeDemo
{

    /// <summary>
    /// Open XML SDK 2.0 for Microsoft Office http://www.microsoft.com/en-us/download/details.aspx?id=5124
    /// Open XML SDK 2.5 for Microsoft Office http://www.microsoft.com/en-us/download/details.aspx?id=30425
    /// Open XML SDK open source  https://github.com/officedev/open-xml-sdk
    /// Open XML SDK 2.5 类库参考 https://msdn.microsoft.com/ZH-CN/library/gg278315.aspx
    /// http://openxmldeveloper.org/
    /// https://github.com/OfficeDev/Open-Xml-PowerTools
    /// https://msdn.microsoft.com/en-us/library/office/bb448854.aspx
    /// https://github.com/OfficeDev
    /// </summary>
    public partial class Form1 : Form
    {

        /// <summary>
        ///
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        ///
        /// </summary>
        public class Package
        {
            public string Company { get; set; }
            public double Weight { get; set; }
            public long TrackingNumber { get; set; }
            public DateTime DateOrder { get; set; }
            public bool HasCompleted { get; set; }
        }
        /// <summary>
        /// 生成EXCEL文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
            string excelPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "geovindu" + timeMark + ".xlsx");
            List<Package> packages =
                 new List<Package>
                        { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L, DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L, DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L, DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L, DateOrder =  DateTime.Today.AddDays(-4), HasCompleted = true },
                          new Package { Company = "Test Works", Weight = 35.8, TrackingNumber = 4665518774L, DateOrder =  DateTime.Today.AddDays(-2), HasCompleted = true },
                          new Package { Company = "Good Works", Weight = 48.8, TrackingNumber = 4665518775L, DateOrder =  DateTime.Today.AddDays(-1), HasCompleted = true },

                        };

            List<string> headerNames = new List<string> { "Company", "Weight", "Tracking Number", "Date Order", "Completed" };
            ExcelFacade excelFacade = new ExcelFacade();
            excelFacade.Create<Package>(excelPath, packages, "Packages", headerNames);
        }

        /// <summary>
        /// 读取工作表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {

            string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.xlsx");
            List<SheetNameInfo> sheets = new List<SheetNameInfo>();
            sheets = GetSheets(file);
            this.comboBox1.DataSource = sheets;
            comboBox1.DisplayMember = "SheetName";
            comboBox1.ValueMember = "SheetID";
            //1
            //OpenXmlOficeDemo.SLExcelUtility.SLExcelReader read = new SLExcelUtility.SLExcelReader();
            //var data = (new OpenXmlOficeDemo.SLExcelUtility.SLExcelReader()).ReadExcel(file);
            //this.dataGridView1.DataSource = data.DataRows;
            //2
            //FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
            //DataTable dt = ReadAsDataTable(file);
            //this.dataGridView1.DataSource = dt;
           // fs.Close();
           // fs.Dispose();

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.xlsx");
            //FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
            DataTable dt = ReadAsDataTable(file);// ReadExcel(this.comboBox1.SelectedText, fs);
            this.dataGridView1.DataSource = dt;
            //fs.Close();
            //fs.Dispose();
        }

        /// <summary>
        /// 读取工作表
        /// EXCEL 2007版以上
        /// </summary>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static List<SheetNameInfo> GetSheets(String strFileName)
        {
            //  Fill this collection with a list of all the sheets.
            List<SheetNameInfo> sheets = new List<SheetNameInfo>();
            using (SpreadsheetDocument xlPackage = SpreadsheetDocument.Open(strFileName, false))
            {

                WorkbookPart workbook = xlPackage.WorkbookPart;
                Stream workbookstr = workbook.GetStream();
                XmlDocument doc = new XmlDocument();
                doc.Load(workbookstr);
                XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
                nsManager.AddNamespace("default", doc.DocumentElement.NamespaceURI);
                XmlNodeList nodelist = doc.SelectNodes("//default:sheets/default:sheet", nsManager);
                int k = 0;
                foreach (XmlNode node in nodelist)
                {
                    SheetNameInfo sheetNameInfo = new SheetNameInfo();
                    String sheetName = String.Empty;
                    sheetName = node.Attributes["name"].Value;
                    sheetNameInfo.SheetID = k;
                    sheetNameInfo.SheetName = sheetName;
                    sheets.Add(sheetNameInfo);
                    k++;
                }
            }
            return sheets;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="stringTablePart"></param>
        /// <returns></returns>
        public static String GetValue(Cell cell, SharedStringTablePart stringTablePart)
        {

            if (cell.ChildElements.Count == 0)
                return null;
            //get cell value
            String value = cell.CellValue.InnerText;
            //Look up real value from shared string table
            if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
                value = stringTablePart.SharedStringTable
                .ChildElements[Int32.Parse(value)]
                .InnerText;
            return value;

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static DataTable ReadAsDataTable(string fileName)
        {
            DataTable dataTable = new DataTable();
            using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileName, false))
            {
                WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
                IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                string relationshipId = sheets.First().Id.Value;
                WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
                Worksheet workSheet = worksheetPart.Worksheet;
                SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();

                foreach (Cell cell in rows.ElementAt(0))
                {
                    dataTable.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                }

                foreach (Row row in rows)
                {
                    DataRow dataRow = dataTable.NewRow();
                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }

                    dataTable.Rows.Add(dataRow);
                }

            }
            dataTable.Rows.RemoveAt(0);

            return dataTable;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="document"></param>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            string value = cell.CellValue.InnerXml;

            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }

  

时间: 2024-10-28 20:25:09

Csharp: read excel file using Open XML SDK 2.5的相关文章

Csharp: create word file using Open XML SDK 2.5

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packagi

csharp:OpenXml SDK 2.0 and ClosedXML read excel file

https://openxmlexporttoexcel.codeplex.com/ 引用: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using DocumentForma

使用OPEN XML SDK 读取EXCEL中的超链接Hyperlink

使用OPEN XML SDK 读取EXCEL中的超链接Hyperlink 原理 先创建一个包含所有EXCEL单元格中超链接Hyperlink数据的表,再定位单元格通过列头(如A1,B1)获取超链接信息.本文仅重着于如何读取EXCEL中的超链接Hyperlink信息,不设计OPEN XML SDK讲解,如果需要请参考: 使用Open XML SDK读取Excel 代码 using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(strea

VSTO学习之路:使用Open XML SDK for Office解析Excel数据

Excel2007以后,工作簿是以XML文本保存数据的,用压缩工具打开工作簿文件,结构大致如下: 文件夹下基本全部是xml文本文件.微软提供了Open XML SDK 2.5 for Office,其中定义了和这些xml文件相关的类,帮助我们使用xml的形式解析工作簿里的数据和内容.跳转到微软官方资料          跳转到Open XML SDK 2.5 for Microsoft Office下载连接 在安装了 Open XML SDK 2.5 之后,在项目或应用程序中,添加对以下组件的引

【转】Open XML SDK class structure

Open XML SDK class structure March 27, 2012 by Vincent I’ve gotten a few questions on the class structure of the Open XML SDK. There are articles on Open XML itself, where you work directly with XML files and tags, and zip them up yourself. Basically

Apache POI – Reading and Writing Excel file in Java

来源于:https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/ In this article, we will discuss about how to read and write an excel file using Apache POI 1. Basic definitions for Apache POI library This section briefly describe a

NetSuite SuiteScript 2.0 export data to Excel file(xls)

In NetSuite SuiteScript, We usually do/implement export data to CSV, that's straight forward: Collect 'encoded' string to Array for column, join them with comma ',' to be a string. Collect each line's data same as column to push to the Array. Join al

Open XML SDK 在线编程黑客松

2015年2月10日-3月20日,开源社 成员 微软开放技术,GitCafe,极客学院联合举办" Open XML SDK 在线编程黑客松 ",为专注于开发提高生产力的应用及服务的程序猿们提供一个在线动手开发,学习交流,技术分享,发挥创意与竞技的盛宴. 我们为参赛队伍准备了丰富的技术干货,国内外高手无私分享以及技术支持,逐步引导的在线学习视频教程与技术文档,场景范例,在线编程及演示环境,社区互动,丰富礼品(如极客学院特别为每位参赛人员提供月VIP码,用户可以免费学习极客学院全网课程)及

Open Xml SDK 引文

什么是Open Xml SDK? 什么是Open Xml? 首先,我们得知道,Open Xml为何物? 我们还是给她起个名字——就叫 “开放Xml”,以方便我们中文的阅读习惯.之所以起开放这个名字,因为以前有接触过Open Authorization,可以称为开放授权,比如OpenID之类的. “Open XML标准的简单介绍:Ecma Office Open XML(“Open XML”)是针对字处理文档.演示文稿和电子表格的国际化开放标准,可免费供多个应用程序在多个平台上实现.Microso