DocumentFormat.OpenXml read excel file
这里向大家介绍一种读取excel 数据的方法,用的是DoucmentFormat.OpenXml.dll
废话不多说,向大家展示一下在项目中处理过的方法,如果有任何疑问,随时联系我。
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks; namespace EArchivePermissionTool
{
public class ExcelDataReader
{
private bool mIsCheck { get; set; }
public ExcelDataReader(bool mIsCheck)
{
this.mIsCheck = mIsCheck;
}
public Dictionary<string, List<List<string>>> GetWholeSheets(Stream stream)
{
Dictionary<string, List<List<string>>> result = null;
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stream, false))
{
result = GetWholeSheets(spreadsheetDocument);
}
}
catch
{ }
finally
{
if (!mIsCheck && stream != null)
{
stream.Dispose();
}
}
return result;
}
private Dictionary<string, List<List<string>>> GetWholeSheets(SpreadsheetDocument spreadsheetDocument)
{
var data = new Dictionary<string, List<List<string>>>();
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
foreach (var worksheetInfo in workbookPart.Workbook.Descendants<Sheet>())
{
if (worksheetInfo.State != null && worksheetInfo.State == SheetStateValues.Hidden)
{
continue;
}
string workSheetName = worksheetInfo.Name;
var sheetData = GetSheetData(workbookPart, (WorksheetPart)workbookPart.GetPartById(worksheetInfo.Id));
data.Add(workSheetName, sheetData);
}
return data;
}
private List<List<string>> GetSheetData(WorkbookPart workbookPart, WorksheetPart worksheetPart)
{
if (worksheetPart == null)
{
throw new Exception("Out of range.");
}
List<List<string>> result = new List<List<string>>();
OpenXmlReader reader = OpenXmlReader.Create(worksheetPart, true);
var rows = worksheetPart.Worksheet.Descendants<Row>();
uint rowIndex = ;
int rowIndexForCheck = ;
foreach (var row in rows)
{
if (row.HasChildren)
{
var currentRowIndex = row.RowIndex.Value;
while (currentRowIndex > rowIndex)
{
result.Add(new List<string>());
++rowIndex; if (mIsCheck)
{
++rowIndexForCheck;
if (rowIndexForCheck == )
{
rowIndexForCheck = ;
break;
}
}
} int columnIndex = ;
List<string> l = new List<string>();
foreach (Cell cell in row.Descendants<Cell>())
{
if (cell.CellReference != null)
{
// Gets the column index of the cell with data
int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference)); if (columnIndex < cellColumnIndex)
{
do
{
l.Add(string.Empty);//Insert blank data here;
columnIndex++;
}
while (columnIndex < cellColumnIndex);
}
}
l.Add(GetCellValue(workbookPart, cell));
columnIndex++;
}
//Changed by EArchive
if (!string.IsNullOrEmpty(l[]))
{
result.Add(l);
}
++rowIndex;
++rowIndexForCheck;
if (mIsCheck && rowIndexForCheck == )
{
break;
}
}
}
return result;
}
/// <summary>
/// Given a cell name, parses the specified cell to get the column name.
/// </summary>
/// <param name="cellReference">Address of the cell (ie. B2)</param>
/// <returns>Column Name (ie. B)</returns>
public static string GetColumnName(string cellReference)
{
// Create a regular expression to match the column name portion of the cell name.
Regex regex = new Regex("[A-Za-z]+");
Match match = regex.Match(cellReference); return match.Value;
}
/// <summary>
/// Given just the column name (no row index), it will return the zero based column index.
/// Note: This method will only handle columns with a length of up to two (ie. A to Z and AA to ZZ).
/// A length of three can be implemented when needed.
/// </summary>
/// <param name="columnName">Column Name (ie. A or AB)</param>
/// <returns>Zero based index if the conversion was successful; otherwise null</returns>
public static int? GetColumnIndexFromName(string columnName)
{
Regex alpha = new Regex("^[A-Z]+$");
if (!alpha.IsMatch(columnName)) throw new ArgumentException(); char[] colLetters = columnName.ToCharArray();
Array.Reverse(colLetters); int convertedValue = ;
for (int i = ; i < colLetters.Length; i++)
{
char letter = colLetters[i];
int current = i == ? letter - : letter - ; // ASCII 'A' = 65
convertedValue += current * (int)Math.Pow(, i);
}
return convertedValue;
} private string GetCellValue(WorkbookPart workbookPart, Cell c)
{
string cellValue = "";
if (c.CellValue == null)
{
return cellValue;
}
if (c.DataType != null && c.DataType == CellValues.SharedString)
{
SharedStringItem ssi = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(int.Parse(c.CellValue.InnerText));
cellValue = ssi.InnerText;
}
else
{
cellValue = c.CellValue.InnerText;
}
return cellValue.Trim();
} }
}
Note: mIsCheck是一个bool值,初始化为true,只会返回每个sheet的header,初始化为false,返回header及body。
DocumentFormat.OpenXml read excel file的更多相关文章
- 使用DocumentFormat.OpenXml操作Excel文件.xlsx
1.开始 DocumentFormat.OpenXml是ms官方给一个操作office三大件新版文件格式(.xlsx,.docx,.pptx)的组件:特色是它定义了OpenXml所包含的所有对象(たぶ ...
- Csharp: read excel file using Open XML SDK 2.5
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- csharp:using OpenXml SDK 2.0 and ClosedXML read excel file
https://openxmlexporttoexcel.codeplex.com/ http://referencesource.microsoft.com/ 引用: using System; u ...
- C# 基于DocumentFormat.OpenXml的数据导出到Excel
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.S ...
- ClosedXML、DocumentFormat.OpenXml导出DataTable到Excel
在很多系统中都用到导出,使用过多种导出方式,觉得ClosedXML插件的导出简单又方便. 并且ClosedXML.DocumentFormat.OpenXml都是MIT开源. 首先通过 Nuget 安 ...
- ExcelDataReader read excel file
上篇文章向大家介绍了用DocumentFormat.OpenXml.dll读取excel的方法,这里再向大家介绍一种轻量级简便的方法,用的是Excel.dll,及ICSharpCode.SharpZi ...
- 一个用微软官方的OpenXml读写Excel 目前网上不太普及的方法。
新版本的xlsx是使用新的存储格式,貌似是处理过的XML. 传统的excel处理方法,我真的感觉像屎.用Oldeb不方便,用com组件要实际调用excel打开关闭,很容易出现死. 对于OpenXML我 ...
- 使用OpenXML将Excel内容读取到DataTable中
前言:前面的几篇文章简单的介绍了如何使用OpenXML创建Excel文档.由于在平时的工作中需要经常使用到Excel的读写操作,简单的介绍下使用 OpenXML读取Excel中得数据.当然使用Open ...
- 用 DocumentFormat.OpenXml 和Microsoft.Office.Interop.Word 写入或者读取word文件
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...
随机推荐
- CAD数据分块,偏移校准,加载到百度地图、高德地图、谷歌等地图上
前面分享过一篇如何将CAD海量数据显示在百度地图上(百度地图Canvas实现十万CAD数据秒级加载),但是很多开发者在CAD数据提取时遇到了问题,所以接下来的文章将介绍如何将CAD数据提取. 准备软件 ...
- TextCNN 代码详解(附测试数据集以及GitHub 地址)
前言:本篇是TextCNN系列的第三篇,分享TextCNN的优化经验 前两篇可见: 文本分类算法TextCNN原理详解(一) 一.textCNN 整体框架 1. 模型架构 图一:textCNN 模型结 ...
- 使用mybatis-generator生成底层
使用mybatis-generator生成底层 前言 使用springboot2,jdk1.8,idea 一.在pom引入相关依赖 <!--mybatise-generator--> ...
- xcode7中搭建python开发环境
1. 双击打开Xcode 2. 点击File->New->New Project 3. 在左边的面板选择Other,右边选择External Build Sytem,点击Next 4. 输 ...
- Another Version of Inversion 二维树状数组求逆序对
Another Version of Inversion 题意:只有2种走路方式,往右或者往下,求先走到一个大的数,在走到小的数的这种方式有多少.也就是说求出关于这个2维矩阵的逆序数. 题解:二维数组 ...
- Go语言os标准库常用方法
1. os.Getwd()函数 原型:func Getwd()(pwd string, err error) 作用:获取当前文件路径 返回:当前文件路径的字符串和一个err信息 示例: package ...
- Unity - 2D中的物理关节
本文概述: 分析Unity中几个2D物理关节组件的基本功能.使用方法.运用场景等 开发环境:Unity2019.3.0a2 / VS2017 项目资源包: 2D Joints Starter 说明: ...
- [大数据学习研究]2.利用VirtualBox模拟Linux集群
1. 在主机Macbook上设置HOST 前文书已经把虚拟机的静态IP地址设置好,以后可以通过ip地址登录了.不过为了方便,还是设置一下,首先在Mac下修改hosts文件,这样在ssh时就不用输入ip ...
- RatingBar星级拖动条
RatingBar和SeekBar用法类似,他们都继承AbsSeekBar类; RatingBar的xml属性 android:numStars="5" 表示有5颗星 andro ...
- 【第九篇】uploadify上传文件
依然不多说,上代码 首先是给文件夹的位置 然后上代码 <div class="upload"> <div class="uploadswf"& ...