vsto c# openxml操作excel

article/2025/10/25 4:05:35

word ppt excel 后缀加rar 都可以解压看到资源文件

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text.RegularExpressions;namespace OpenXmlTest
{class TLExcel{#region 全局属性及方法public static int TLOK = 0;public static int TLERR = -1;public static void ShowMessage(string strMsg){Console.WriteLine(strMsg);}#endregion#region 私有属性private SpreadsheetDocument _spreadsheetDocument;#endregionpublic TLExcel(){ }/* 打开EXCEL */public int Open(string szPath) {try{_spreadsheetDocument = SpreadsheetDocument.Open(szPath, true);if (null == _spreadsheetDocument)return TLERR;return TLOK;}catch (Exception ex){ShowMessage("[Func:Open], Exception:" + ex.Message);return TLERR;}}/* 创建EXCEL */public int Create(string szPath){try{_spreadsheetDocument = SpreadsheetDocument.Create(szPath, SpreadsheetDocumentType.Workbook);// Add a WorkbookPart to the document.WorkbookPart workbookpart = _spreadsheetDocument.AddWorkbookPart();workbookpart.Workbook = new Workbook();// Add a WorksheetPart to the WorkbookPart.WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();worksheetPart.Worksheet = new Worksheet(new SheetData());// Add Sheets to the Workbook.Sheets sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());// Append a new worksheet and associate it with the workbook.Sheet sheet = new Sheet() { Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };sheets.Append(sheet);workbookpart.Workbook.Save();return TLOK;}catch (Exception ex){ShowMessage("[Func:Create], Exception:" + ex.Message);return TLERR;}}/* 保存Excel */public void Save(){try{_spreadsheetDocument.WorkbookPart.Workbook.Save();}catch (Exception ex){ShowMessage("[Func:Save],Exception:" + ex.Message);}}/* 关闭Excel */public void Close(){try{this.Save();    //先保存_spreadsheetDocument.Close();}catch (Exception ex){ShowMessage("[Func:Save],Exception:" + ex.Message);}}#region 读写EXCEL/// <summary>/// 读取单元格数据/// </summary>/// <param name="iSheetNum">Sheet编号</param>/// <param name="iRowNum">行号</param>/// <param name="strColName">列名</param>/// <param name="iColNum">返回的单元格数据</param>/// <returns>状态</returns>public int ReadCellValue(int iSheetNum, uint iRowNum, string strColName, ref string strValue){Worksheet sheet = GetSpreadsheetWorksheet(iSheetNum);if (null == sheet){return TLERR;}Cell cell = GetSpreadsheetCell(sheet, strColName, iRowNum);if (null == cell){strValue = null;return TLERR;}string value = cell.CellValue.InnerText;SharedStringTablePart shareStringPart = this.GetSharedStringTable();strValue = shareStringPart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;return TLOK;}//写入数据public int WriteCellValue(int iSheetNum, uint iRowNum, string strColName, string strValue){//bool bIsNewCell = false;    //是否是新单元格Worksheet sheet = GetSpreadsheetWorksheet(iSheetNum);if (null == sheet){return TLERR;}// Get the SharedStringTablePart and add the result to it.// If the SharedStringPart does not exist, create a new one.SharedStringTablePart shareStringPart = this.GetSharedStringTable();Cell cell = GetSpreadsheetCell(sheet, strColName, iRowNum);if (null == cell){//插入一个单元格cell = InsertCellInWorksheet(strColName, iRowNum, sheet);int iIndex = InsertSharedStringItem(strValue, shareStringPart);// Set the value of the cell.cell.CellValue = new CellValue(iIndex.ToString());cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);}else{int iIndex;if (null == cell.CellValue){cell.CellValue = new CellValue();iIndex = InsertSharedStringItem(strValue, shareStringPart);cell.CellValue.Text = iIndex.ToString();}else { iIndex = Int32.Parse(cell.CellValue.Text);}OpenXmlElement xmlElement = shareStringPart.SharedStringTable.ChildElements[iIndex];((SharedStringItem)xmlElement).Text.Text = strValue;}return TLOK;}#endregion//获取行数public int GetRowsAndCols(int iSheetNum, ref int iRows){Worksheet workSheet = GetSpreadsheetWorksheet(iSheetNum);if (null == workSheet){return TLERR;}IEnumerable<Row> rows = workSheet.Descendants<Row>();iRows = rows.Count();return TLOK;}//获取Sheet数目public int GetWorksheetNumber(){IEnumerable<Sheet> sheets = _spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>();return sheets.Count();}//获取sheetNamepublic int GetWorksheetName(int iSheetNum, ref string strSheetName){IEnumerable<Sheet> sheets = _spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.SheetId == iSheetNum);if (1 != sheets.Count()){ShowMessage("[Func:ReadCellValue], 指定的Sheet不存在");return TLERR;}strSheetName = sheets.First().Name;return TLOK;}private Sheet GetSheet(int iSheetNum){IEnumerable<Sheet> sheets = _spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.SheetId == iSheetNum);if (1 != sheets.Count()){ShowMessage("[Func:ReadCellValue], 指定的Sheet不存在");return null;}return sheets.First();}private Sheet GetSheet(string strSheetName){IEnumerable<Sheet> sheets = _spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == strSheetName);if (1 != sheets.Count()){ShowMessage("[Func:ReadCellValue], 指定的Sheet不存在");return null;}return sheets.First();}private SharedStringTablePart GetSharedStringTable(){SharedStringTablePart shareStringPart;if (_spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0){shareStringPart = _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();}else{shareStringPart = _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();}return shareStringPart;}//获取workSheetprivate Worksheet GetSpreadsheetWorksheet(int iSheetNum){Sheet sheet = GetSheet(iSheetNum);if (null == sheet)return null;WorksheetPart worksheetPart = (WorksheetPart)_spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);Worksheet worksheet = worksheetPart.Worksheet;return worksheet;}//获取workSheetprivate Worksheet GetSpreadsheetWorksheet(string strSheetName){Sheet sheet = GetSheet(strSheetName);if (null == sheet)return null;WorksheetPart worksheetPart = (WorksheetPart)_spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);Worksheet worksheet = worksheetPart.Worksheet;return worksheet;}// Given a worksheet, a column name, and a row index, gets the cell at the specified column and row.private static Cell GetSpreadsheetCell(Worksheet worksheet, string columnName, uint rowIndex){IEnumerable<Row> rows = worksheet.GetFirstChild<SheetData>().Elements<Row>().Where(r => r.RowIndex == rowIndex);if (rows.Count() == 0){// A cell does not exist at the specified row.return null;}IEnumerable<Cell> cells = rows.First().Elements<Cell>().Where(c => string.Compare(c.CellReference.Value, columnName + rowIndex, true) == 0);if (cells.Count() == 0){// A cell does not exist at the specified column, in the specified row.return null;}return cells.First();}// Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. // If the cell already exists, returns it. private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, Worksheet worksheet/*WorksheetPart worksheetPart*/){//Worksheet worksheet = worksheetPart.Worksheet;SheetData sheetData = worksheet.GetFirstChild<SheetData>();string cellReference = columnName + rowIndex;// If the worksheet does not contain a row with the specified row index, insert one.Row row;if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0){row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();}else{row = new Row() { RowIndex = rowIndex };sheetData.Append(row);}// If there is not a cell with the specified column name, insert one.  if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0){return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();}else{// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.Cell refCell = null;foreach (Cell cell in row.Elements<Cell>()){if (string.Compare(cell.CellReference.Value, cellReference, true) > 0){refCell = cell;break;}}Cell newCell = new Cell() { CellReference = cellReference };row.InsertBefore(newCell, refCell);worksheet.Save();return newCell;}}// Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text // and inserts it into the SharedStringTablePart. If the item already exists, returns its index.private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart){// If the part does not contain a SharedStringTable, create it.if (shareStringPart.SharedStringTable == null){shareStringPart.SharedStringTable = new SharedStringTable();}int i = 0;foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>()){if (item.InnerText == text){// The text already exists in the part. Return its index.return i;}i++;}// The text does not exist in the part. Create the SharedStringItem.shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));shareStringPart.SharedStringTable.Save();return i;}}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text.RegularExpressions;
using Excel = Microsoft.Office.Interop.Excel;namespace OpenXmlTest
{class Program{public static void UseCommom(){Excel.Application excelApp = new Excel.Application();Excel.Workbook expWorkBookConfig = null;//EXCEL 产品配置文件 (中文)Excel.Workbooks expWorkBooks = null;//打开Excle文件 创建表格对象excelApp.Visible = false; excelApp.DisplayAlerts = false;try{expWorkBooks = excelApp.Workbooks;expWorkBookConfig = expWorkBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Worksheet sheet = expWorkBookConfig.Worksheets[1];for (int iLine = 1; iLine < 200; iLine++){for (char ch = 'A'; ch <= 'Z'; ch++){string str = string.Format("{0}", ch);Excel.Range ACell = sheet.get_Range(str + iLine.ToString(), System.Reflection.Missing.Value);ACell.Value2 = "TestTestTestTestTestTestTestTestTestTestTestTestTestTestTest";}}expWorkBookConfig.SaveAs(@"D:\OpenXmlTest\bin\Release\Commom.xlsx",System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value);expWorkBookConfig.Close();excelApp.Quit();}catch (System.Exception ex){Console.WriteLine(ex.Message);excelApp.Quit();expWorkBookConfig = null;excelApp = null;}GC.Collect();}public static void UseOpenXml(){TLExcel doc = new TLExcel();if (TLExcel.TLOK == doc.Create("OpenXml.xlsx")){Console.WriteLine("开始时间:" + DateTime.Now);for (int iLine = 1; iLine < 200; iLine++){for (char ch = 'A'; ch <= 'Z'; ch++){string str = string.Format("{0}", ch);doc.WriteCellValue(1, (uint)iLine, str, "TestTestTestTestTestTestTestTestTestTestTestTestTestTestTest");}}Console.WriteLine("结束时间:" + DateTime.Now);}doc.Close();}static void Main(string[] args){Console.WriteLine("OpenXml:");UseOpenXml();Console.WriteLine("Commom:");Console.WriteLine("开始时间:" + DateTime.Now);UseCommom();Console.WriteLine("结束时间:" + DateTime.Now);Console.ReadKey();}}
}

http://officeopenxml.com/anatomyofOOXML-xlsx.php

https://www.ecma-international.org/publications-and-standards/standards/ecma-376/


http://chatgpt.dhexx.cn/article/LMIn8iq9.shtml

相关文章

java openxml word_OpenXml读取word内容的实例

OpenXml读取word内容注意事项 1、使用OpenXml读取word内容&#xff0c;word后缀必须是".docx"&#xff1b;如果word后缀是".doc"需要转成".docx"后&#xff0c;才可以读取&#xff1b; 2、需要引入相关dll&#xff1b;"WindowsBase.dll&quo…

C# + OpenXML 生成 Word 文档(VS2015)

本文是 Open XML SDK 的入门文章&#xff0c;将逐步讲解如何生成一个下面这样的 Word 文档&#xff1a; 有关 Open XML SDK 的详细内容&#xff0c;请参阅这个链接&#xff1a;欢迎使用 Open XML SDK 2.5 for Office 创建示例程序 启动 Visual Studio 2015&#xff0c;新建一…

c# openxml Excel部分学习之路

c# openxml Excel部分学习之路 Openxml学习工具 Openxml学习工具 Open XML SDK 2.5 Productivity Tool&#xff0c;使用本工具可以对比原文档和进行更改后的文档发生的变化&#xff0c;便于我们能够理解我们对文档所作的操作带来了什么改变。 比如我们新建了两个Excel文件在新…

mysql openxml_OpenXML SDK2.0初窥

让我们直奔主题吧! 下载地址:http://www.microsoft.com/downloads/details.aspx?FamilyIdC6E744E5-36E9-45F5-8D8C-331DF206E0D0 官方论坛:http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/threads 其它资源:http://msdn.microsoft.com/en-us/librar 让我们直奔主题吧…

dotnet OpenXML PPT 动画框架入门

本文将从 OpenXML 方面聊 PPT 的动画框架&#xff0c;本文是属于编程方面而不是 PPT 动画制作教程 开始之前&#xff0c;还请掌握一些基础知识&#xff0c;如阅读以下博客 C# dotnet 使用 OpenXml 解析 PPT 文件Office 文档解析 文档格式和协议dotnet OpenXML 解析 PPT 页面元…

java openxml word_【转】【OpenXml】OpenXml操作Word的一些操作总结

OpenXml相对于用MS提供的COM组件来生成WORD,有如下优势: 1.相对于MS 的COM组件,因为版本带来的不兼容问题,及各种会生成WORD半途会崩溃的问题. 2.对比填满一张30多页的WORD来说(包含图,表等),用COM组件来生成会占用20秒,Openxml1秒. 3.MS Word软件太贵了,你的客户装的是开源WOR…

java openxml 操作 word_OpenXML操作word

OpenXML概述 项目中经常需要操作word,之前的方式是采用COM接口,这个接口很不稳定,经常报错。现在开始采用OpenXML。OpenXML(OOXML)是微软在Office 2007中提出的一种新的文档格式,Office 2007中的Word、Excel、PowerPoint默认均采用OpenXML格式 。 OpenXml相对于用MS提供的C…

openXMl

openXMl注意点 一、基础标签 w:pStyle 定义样式ID w:keepNext &#xff1a;段落是否在一个页面上 w:keepLines &#xff1a;此元素指定在页面视图中呈现该文档时&#xff0c;尽可能将该段落的所有行维护在单个页面上 w:widowControl &#xff1a;这个元素指定消费者是否应该通…

OpenXML库(office文档读写库)的安装

本体安装 OpenXml库是由微软维护的一个开源的Office文档读写库&#xff0c;其与其他类似用途的库的比较可以看到这篇文章。 在C#中使用OpenXml非常简单&#xff0c;只需要使用NuGet安装其程序包即可&#xff0c;流程如下(NuGet这东西真的是个神器啊&#xff01;)&#xff1a;…

java e.getmessage() null_Java e.getMessage 错误信息为null

解决方案&#xff1a;用e.printStackTrace() e.getMessage()为null也很正常&#xff0c;NullPointException的getMessage()就为null 我在抛出Exception时也可以直接 throw new MyException(); 这样getMessage()返回的就是null了 这几天做的项目&#xff0c;测试小组说测出来的…

java中getmessage函数_PeekMessage、GetMessage的区别

在Windows编程中经常使用这两个函数来处理消息&#xff0c;它们之间的区别就是GetMessage是阻塞的&#xff0c;PeekMessage是非阻塞的。 GetMessage原型如下&#xff1a;BOOL GetMessage(LPMSG lpMsg,HWND hWnd,UINT wMsgFilterMin,UINT wMsgFilterMax); PeekMessage原型如下&a…

java e.getmessage() null,Java 求助! 为什么我拿不到错误信息,e.getMessage()

Java 求助! 为什么我拿不到错误信息,e.getMessage() Java 求助! 为什么我拿不到错误信息,e.getMessage() 我明明打印了错误信息的啊? e.getMessage() 是空,为什么? 一声声带着惊讶,带着恐慌,带着质疑,带着无奈的话语,从某个角落里传出。 议论纷纷...... 似乎拿不到异…

Java 异常中 e.getMessage() 和 e.toString() e.printStackTrace()的区别常见的几种异常

Java 异常中 e.getMessage() 和 e.toString() e.printStackTrace()的区别 一、概述 在java异常体系中&#xff0c;要打印异常信息&#xff0c;可以通过&#xff1a;e.getMessage() 、 e.toString() e.printStackTrace() 等方法打印出 一些 异常信息。已知的是这些方法都可以打…

GetMessage以及消息循环说明

GetMessage以及消息循环说明 在创建窗口、显示窗口、更新窗口后&#xff0c;我们需要编写一个消息循环&#xff0c;不断地从消息队列中取出消息&#xff0c;并进行响应。要从消息队列中取出消息&#xff0c;我们需要调用GetMessage()函数&#xff0c;该函数的原型声明如下&…

redis使用配置文件的方式启动

文章目录 为什么用配置文件启动呢使用配置文件启动1.创建配置文件2.修改配置文件里面的参数3.以配置文件的方式启动4.查看日志文件 为什么用配置文件启动呢 因为在企业项目中不会只有单个redis实例&#xff0c;每个redis的config配置都可以能不一样&#xff0c;所以这个时候就需…

.NET Core使用Redis

环境Windows 首先安装Redis 1、下载最新版redis&#xff0c;选择.zip则是免安装的版本 下载地址&#xff1a;https://github.com/MicrosoftArchive/redis/releases 2、解压到指定目录&#xff0c;并运行cmd命令 3、在该文件夹下运行命令&#xff1a;redis-server.exe redis.…

flask使用redis

文章目录 前言一、环境二、使用步骤1.安装redis1.下载2.运行 2.安装并使用redis包1.安装2.使用 运行 前言 有人会有疑问&#xff0c;不是已经连上了mysql数据库了吗&#xff0c;为什么还要用redis数据库?有时候用户访问网页的时候&#xff0c;会产生一些临时性的数据&#xf…

最新版本Redis:Redis 7.0 安装使用,编译安装Redis,Redis使用场景-2022年最新Redis图解安装

最新版本Redis&#xff1a;Redis 7.0 安装使用&#xff0c;编译安装Redis&#xff0c;Redis使用场景。 本章主要目标&#xff1a; 1.Redis介绍 2.下载Redis&#xff0c;编译安装Redis 3.启动Redis使用 4.Redis常用数据类型 5.使用场景介绍 下面开始本章内容的学习 1.Redi…

TP5 使用redis

1.打开tp5官方手册&#xff0c;在缓存下面找到使用多个缓存类型 粘贴以下代码到tp框架config下面的缓存设置下 // 切换到redis操作 Cache::store(redis)->set(name,value);//获取redis Cache::store(redis)->get(rename); //实现redis 消息队列 在 /thinkphp/library/t…

C#使用Redis

Redis是一种key-value型数据库与非持久化数据,用来存于频繁操作的数据&#xff0c;与Sqlserver、Mysql等关系型数据库有着很大的区别&#xff0c;如Redis存储的数据结构不相同&#xff0c;还有Redis数据存于内存中&#xff0c;它也与Mongodb、Azure Cosmos Db、Azure TableStor…