OpenXml读写Excel实例代码

新版本的xlsx是使用新的存储格式,貌似是处理过的XML。

对于OpenXML我网上搜了一下,很多人没有介绍。所以我就这里推荐下,相信会成为信息系统开发的必备。

先写出个例子,会发现如此的简介:

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using XFormular.config;
using System.IO;
using com.xtar.amfx;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;

namespace XFormular.test
{
    class Class1
    {
        public void test()
        {
            DataTable table = new DataTable("1");
            table.Columns.Add("2");
            for (int i = 0; i < 10; i++)
            {
                DataRow row = table.NewRow();
                row[0] = i;
                table.Rows.Add(row);
            }

List<DataTable> lsit = new List<DataTable>();
            lsit.Add(table);

OpenXmlSDKExporter.Export(AppDomain.CurrentDomain.BaseDirectory + "\\excel.xlsx", lsit);
        }
    }
}

写出代码

代码如下:

using System;
using System.IO;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Extensions;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;

namespace XFormular
{
    class OpenXmlSDKExporter
    {
        private static string[] Level = {"A", "B", "C", "D", "E", "F", "G",
    "H", "I", "G", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
    "U", "V", "W", "X", "Y", "Z" };

public static List<DataTable> Import(string path)
        {
            List<DataTable> tables = new List<DataTable>();

if (path.EndsWith(ExcelHelper.POSTFIX_SVN))
                return tables;

using (MemoryStream stream = SpreadsheetReader.StreamFromFile(path))
            {
                using (SpreadsheetDocument doc = SpreadsheetDocument.Open(stream, true))
                {
                    foreach (Sheet sheet in doc.WorkbookPart.Workbook.Descendants<Sheet>())
                    {
                        DataTable table = new DataTable(sheet.Name.Value);

WorksheetPart worksheet = (WorksheetPart)doc.WorkbookPart.GetPartById(sheet.Id);

List<string> columnsNames = new List<string>();

foreach (Row row in worksheet.Worksheet.Descendants<Row>())
                        {
                            foreach (Cell cell in row)
                            {
                                string columnName = Regex.Match(cell.CellReference.Value, "[a-zA-Z]+").Value;

if (!columnsNames.Contains(columnName))
                                {
                                    columnsNames.Add(columnName);
                                }

}
                        }

columnsNames.Sort(CompareColumn);

foreach (string columnName in columnsNames)
                        {
                            table.Columns.Add(columnName);
                        }

foreach (Row row in worksheet.Worksheet.Descendants<Row>())
                        {
                            DataRow tableRow = table.NewRow();
                            table.Rows.Add(tableRow);

foreach (Cell cell in row)
                            {
                                string columnName = Regex.Match(cell.CellReference.Value, "[a-zA-Z]+").Value;
                                tableRow[columnName] = GetValue(cell, doc.WorkbookPart.SharedStringTablePart);
                            }
                        }

if (table.Rows.Count <= 0)
                            continue;
                        if (table.Columns.Count <= 0)
                            continue;

tables.Add(table);
                    }
                }
            }

return tables;
        }

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;

}

public static void Export(string path, List<DataTable> tables)
        {
            using (MemoryStream stream = SpreadsheetReader.Create())
            {
                using (SpreadsheetDocument doc = SpreadsheetDocument.Open(stream, true))
                {
                    SpreadsheetWriter.RemoveWorksheet(doc, "Sheet1");
                    SpreadsheetWriter.RemoveWorksheet(doc, "Sheet2");
                    SpreadsheetWriter.RemoveWorksheet(doc, "Sheet3");

foreach (DataTable table in tables)
                    {
                        WorksheetPart sheet = SpreadsheetWriter.InsertWorksheet(doc, table.TableName);
                        WorksheetWriter writer = new WorksheetWriter(doc, sheet);

SpreadsheetStyle style = SpreadsheetStyle.GetDefault(doc);

foreach (DataRow row in table.Rows)
                        {
                            for (int i = 0; i < table.Columns.Count; i++)
                            {
                                string columnName = SpreadsheetReader.GetColumnName("A", i);
                                string location = columnName + (table.Rows.IndexOf(row) + 1);
                                writer.PasteText(location, row[i].ToString(), style);
                            }
                        }

writer.Save();
                    }
                    SpreadsheetWriter.StreamToFile(path, stream);//保存到文件中
                }
            }
        }

private static int CompareColumn(string x, string y)
        {
            int xIndex = Letter_to_num(x);
            int yIndex = Letter_to_num(y);
            return xIndex.CompareTo(yIndex);
        }

/// <summary>
        /// 数字26进制,转换成字母,用递归算法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string Num_to_letter(int value)
        {
            //此处判断输入的是否是正确的数字,略(正在表达式判断)
            int remainder = value % 26;
            //remainder = (remainder == 0) ? 26 : remainder;
            int front = (value - remainder) / 26;
            if (front < 26)
            {
                return Level[front - 1] + Level[remainder];
            }
            else
            {
                return Num_to_letter(front) + Level[remainder];
            }
            //return "";
        }

/// <summary>
        /// 26进制字母转换成数字
        /// </summary>
        /// <param name="letter"></param>
        /// <returns></returns>
        private static int Letter_to_num(string str)
        {
            //此处判断是否是由A-Z字母组成的字符串,略(正在表达式片段)
            char[] letter = str.ToCharArray(); //拆分字符串
            int reNum = 0;
            int power = 1; //用于次方算值
            int times = 1;  //最高位需要加1
            int num = letter.Length;//得到字符串个数
            //得到最后一个字母的尾数值
            reNum += Char_num(letter[num - 1]);
            //得到除最后一个字母的所以值,多于两位才执行这个函数
            if (num >= 2)
            {
                for (int i = num - 1; i > 0; i--)
                {
                    power = 1;//致1,用于下一次循环使用次方计算
                    for (int j = 0; j < i; j++)           //幂,j次方,应该有函数
                    {
                        power *= 26;
                    }
                    reNum += (power * (Char_num(letter[num - i - 1]) + times));  //最高位需要加1,中间位数不需要加一
                    times = 0;
                }
            }
            //Console.WriteLine(letter.Length);
            return reNum;
        }

/// <summary>
        /// 输入字符得到相应的数字,这是最笨的方法,还可用ASIICK编码;
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private static int Char_num(char ch)
        {
            switch (ch)
            {
                case 'A':
                    return 0;
                case 'B':
                    return 1;
                case 'C':
                    return 2;
                case 'D':
                    return 3;
                case 'E':
                    return 4;
                case 'F':
                    return 5;
                case 'G':
                    return 6;
                case 'H':
                    return 7;
                case 'I':
                    return 8;
                case 'J':
                    return 9;
                case 'K':
                    return 10;
                case 'L':
                    return 11;
                case 'M':
                    return 12;
                case 'N':
                    return 13;
                case 'O':
                    return 14;
                case 'P':
                    return 15;
                case 'Q':
                    return 16;
                case 'R':
                    return 17;
                case 'S':
                    return 18;
                case 'T':
                    return 19;
                case 'U':
                    return 20;
                case 'V':
                    return 21;
                case 'W':
                    return 22;
                case 'X':
                    return 23;
                case 'Y':
                    return 24;
                case 'Z':
                    return 25;
            }
            return -1;
        }
    }
}

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace xtar_biz_codegen
{
    class ExcelHelper
    {
        public static string POSTFIX_97 = "XLS";

public static string POSTFIX_03 = "XLSX";
    }
}

(0)

相关推荐

  • 使用c#在word文档中创建表格的方法详解

    复制代码 代码如下: public string CreateWordFile()        {            string message = "";            try            {                Object Nothing = System.Reflection.Missing.Value;                string name = "xiehuan.doc";               

  • c#开发word批量转pdf源码分享

    微软Office Word本身已经提供了另存为PDF文档功能,对于少量文档,手工使用该方式进行Word转换为PDF尚可,一旦需要处理大量的文档,可能就显得有些捉襟见肘了.不过对于已经安装有Office环境,借助一些简单的代码即可实现批量Word转PDF了. 源码: 复制代码 代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.D

  • C#实现word文件下载的代码

    效果: 思路: 简单的有两种方式下载,一种是流下载,一种是WriteFile下载.以下是使用WriteFile下载. 代码: 复制代码 代码如下: protected void LinkButton1_Click(object sender, EventArgs e)        {            try            {                //WriteFile实现下载(word)                string fileName = "qingpin

  • C#采用OpenXml给word里面插入图片

    本文实例讲述了C#采用OpenXml给word里面插入图片的方法,分享给大家供大家参考.具体分析如下: 首先需要指出的是在MSDN官网有完整的OpenXML教程,虽然是全英文的不过还是很有帮助的. 注,原来摘抄代码里面没有模板,在copy过来发现插入word中的图片大小不一样,我们如何查找设置图片大小带代码的那一块,建议自己用在word里面插入一张图片,通过OpenXml Tools 反编译出C#代码,然后改变图片的大小,再次反编译. 使用byeond compare [http://www.s

  • C#生成word记录实例解析

    本文以实例形式讲述了C#生成Word记录的方法,具体实现代码如下: private void button1_Click(object sender, System.EventArgs e) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc是预定义的bookmark */ //创建一个document. Word._Application

  • C#采用OpenXml给Word文档添加表格

    本文实例讲述了C#采用OpenXml给Word文档添加表格的方法,是非常实用的操作技巧.分享给大家供大家参考.具体分析如下: 这里将展示如何使用Openxml向Word添加表格. 代码中表头和数据我们用的同一个TableRow来添加,其实可以通过TableHeader来,其实都一样.后面我们还会进一步给出如何设置单元格样式.表头那一行可以自己通过设置样式来控制 示例代码如下: using System; using System.Collections.Generic; using System

  • C#利用Openxml读取Excel数据实例

    本文实例讲述了C#利用Openxml读取Excel数据的方法,分享给大家供大家参考.具体分析如下: 这里有些问题,如果当Cell 里面是 日期和浮点型的话,对应的Cell.DataType==Null,对应的时间会转换为一个浮点型,对于这块可以通过DateTime.FromOADate(double d)转换为时间. 可是缺点的地方就是,如果Cell.DataType ==NULL, 根本无法确认这个数据到底是 浮点型还是[被转换为了日期的浮点数].查阅了很多国外资料,的确国外博客有一部分都反映

  • C#采用OpenXml实现给word文档添加文字

    本文实例讲述了C#采用OpenXml实现给word文档添加文字的方法,分享给大家供大家参考.具体方法如下: 一般来说,使用OpenXml给word文档添加文字,每个模块都有自己对于的属性以及内容,要设置样式就先声明属性对象,将样式Append到属性里面,再将属性append到模块里面,那么模块里面的内容就具备该样式了.此方法默认是在文件后面追加内容 示例代码如下: using System; using System.Collections.Generic; using System.Linq;

  • C#实现合并多个word文档的方法

    本文实例讲述了C#实现合并多个word文档的方法,是非常具有实用价值的技巧.分享给大家供大家参考. 具体实现方法如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Office.Interop.Word; using System.Reflection; using System.IO; using System.Diagnostics;

  • 使用C#实现在word中插入页眉页脚的方法

    针对Word的操作是很多程序都具备的功能,本文即以实例展示使用C#实现在word中插入页眉页脚的方法,供大家参考借鉴,具体方法如下: 一.插入页脚的方法: public void InsertFooter(string footer) { if (ActiveWindow.ActivePane.View.Type == WdViewType.wdNormalView || ActiveWindow.ActivePane.View.Type == WdViewType.wdOutlineView)

  • C#实现通过模板自动创建Word文档的方法

    本文实例讲述了C#实现通过模板自动创建Word文档的方法,是非常实用的技巧.分享给大家供大家参考.具体实现方法如下: 引言:前段时间有项目要用c#生成Word格式的计算报告,通过网络查找到很多内容,但是都很凌乱,于是自己决定将具体的步骤总结整理出来,以便于更好的交流和以后相似问题可以迅速的解决! 现通过具体的示例演示具体的步骤:   第一步,制作模板   1.新建一个文档,设置文档内容. 2.在相应位置插入书签:将鼠标定位到要插入书签的位置,点击"插入">"书签&quo

随机推荐