OpenXml读写Excel实例代码
发布时间:2023-09-10 18:11:22
新版本的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";
}
}


猜你喜欢
- 对象嵌套关联查询一对多List集合查询mybatis嵌套关联查询如下由于我的是一对集合查询,所以我有两个类。@Data@TableName(
- 小伙伴们,最近比较忙,没什么时间写,今天给大家分享的是JAVA如何导出EXCEL表格,因为最近有做这样一个功能,所以分享出来,如有不对之处,
- 如何查看 Java 的字节码文件?在 Java 中,字节码文件.class实际上是二进制文件,并不能直接查看。要想查看,我们只能通过反编译对
- 手写一个通用加载中、显示数据、加载失败、空数据的LoadingView框架。定义3个布局:加载中,加载失败,空数据加载中:<?xml
- 前言开发项目中需要进行单文件多文件的上传功能,下面演示的ApiResponse是自己分装的返回值,要根据自己的项目来完成。使用的mvvm框架
- 1. 使用ApplicationEventPublisher 发布事件复制下面全部代码,右键包名,粘贴即可生成java类,执行即可看到效果。
- 记录Java执行groovy脚本的两种方式,简单粗暴:一种是通过脚本引擎ScriptEngine提供的eval(String)方法执行脚本内
- 1、xml代码:<?xml version="1.0" encoding="utf-8"?&g
- 1、反射的概念1、概念反射,指在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法,对任意一个对象,都能调用它的任意一个方法。这种
- 有时我们可能会遇到下图这样一种情况 — 我们需要的资料或教程被分成了几部分存放在多个PDF文件中,不管是阅读还是保存都不是很方便,这时我们肯
- 实现备份短信到xml文件和像短信中插入一条数据一、实现短信将备份到xml文件中在布局文件中定义一个按钮,定义点击事件为copyClickMa
- 针对字符串是数字和字母结合而进行的,如"a20"和"a9";比较而得出结果是"a20&qu
- 使用INI配置文件,简单便捷。该辅助工具类为C#操作INI文件的辅助类,源码在某位师傅的基础上完善的来,因为忘记最初的来源了,因此不能提及引
- 本文实例讲述了Java继承Thread类创建线程类。分享给大家供大家参考,具体如下:一 点睛通过继承Thread类创建线程并启动多线程的步骤
- 1.try-catch异常处理说明Java提供try和catch块来处理异常,try块用于包含可能出错的代码。catch块用于处理try块中
- 在分支较多的时候,switch的效率比if高,在反汇编中我们即可看到效率高的原因一、switch语句1、在正向编码时,switch语句可以看
- 项目中用到用户定义运算公式进行就算的需求,这样需要进行字符串四则运算解析,下面提供字符串公式四则运算解析与计算工具类,需要的同学可参考。工具
- Android应用强制更新的用途十分广泛,特别上刚上线的应用肯定会存在或多或少的bug,特别是涉及移动支付这一块的内容,如果出错了会造成比较
- Assets文件介绍assets文件夹里面的文件都是保持原始的文件格式,需要用AssetManager以字节流的形式读取文件。 1. 先在A
- C#使用GET、POST请求获取结果,这里以一个简单的用户登陆为例。1、 使用GET请求获取结果1.1 创建LoginHandler.asp