这里向大家介绍一种读取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的更多相关文章

  1. 使用DocumentFormat.OpenXml操作Excel文件.xlsx

    1.开始 DocumentFormat.OpenXml是ms官方给一个操作office三大件新版文件格式(.xlsx,.docx,.pptx)的组件:特色是它定义了OpenXml所包含的所有对象(たぶ ...

  2. Csharp: read excel file using Open XML SDK 2.5

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  3. csharp:using OpenXml SDK 2.0 and ClosedXML read excel file

    https://openxmlexporttoexcel.codeplex.com/ http://referencesource.microsoft.com/ 引用: using System; u ...

  4. C# 基于DocumentFormat.OpenXml的数据导出到Excel

    using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.S ...

  5. ClosedXML、DocumentFormat.OpenXml导出DataTable到Excel

    在很多系统中都用到导出,使用过多种导出方式,觉得ClosedXML插件的导出简单又方便. 并且ClosedXML.DocumentFormat.OpenXml都是MIT开源. 首先通过 Nuget 安 ...

  6. ExcelDataReader read excel file

    上篇文章向大家介绍了用DocumentFormat.OpenXml.dll读取excel的方法,这里再向大家介绍一种轻量级简便的方法,用的是Excel.dll,及ICSharpCode.SharpZi ...

  7. 一个用微软官方的OpenXml读写Excel 目前网上不太普及的方法。

    新版本的xlsx是使用新的存储格式,貌似是处理过的XML. 传统的excel处理方法,我真的感觉像屎.用Oldeb不方便,用com组件要实际调用excel打开关闭,很容易出现死. 对于OpenXML我 ...

  8. 使用OpenXML将Excel内容读取到DataTable中

    前言:前面的几篇文章简单的介绍了如何使用OpenXML创建Excel文档.由于在平时的工作中需要经常使用到Excel的读写操作,简单的介绍下使用 OpenXML读取Excel中得数据.当然使用Open ...

  9. 用 DocumentFormat.OpenXml 和Microsoft.Office.Interop.Word 写入或者读取word文件

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...

随机推荐

  1. Leetcode之二分法专题-154. 寻找旋转排序数组中的最小值 II(Find Minimum in Rotated Sorted Array II)

    Leetcode之二分法专题-154. 寻找旋转排序数组中的最小值 II(Find Minimum in Rotated Sorted Array II) 假设按照升序排序的数组在预先未知的某个点上进 ...

  2. Leetcode之深度优先搜索(DFS)专题-1020. 飞地的数量(Number of Enclaves)

    Leetcode之深度优先搜索(DFS)专题-1020. 飞地的数量(Number of Enclaves) 深度优先搜索的解题详细介绍,点击 给出一个二维数组 A,每个单元格为 0(代表海)或 1( ...

  3. “adobe premiere中画面和声音不同步” 解决方法

    一.背景 之前在segmentfault上过直播课,直播课有录制回播功能:尝试听了下直播课,发现视频太长了,感觉听起来非常花费学员的时间,在回放中其实有一些直播课里面的内容并不需要,所以准备剪辑一下, ...

  4. Win10安装Linux系统

    windows系统安装虚拟机,常见的是利用VMware Workstation这款软件来进行安装.在未接触Docker之前,我一直通过这款软件来进行管理的.docker是运行在linux环境下的,那怎 ...

  5. NLP(四) 正则表达式

    * + ? * :0个或多个 + :1个或多个 ? :0个或1个 re.search()函数,将str和re匹配,匹配正确返回True import re # 匹配函数,输入:文本,匹配模式(即re) ...

  6. Python字典排序问题

    字典的问题 navagation: 1.问题来源 2.dict的学习 *3.numpy的应用 1.问题来源 在做cs231n,assigment1-kNN实现的时候,需要对一个列表中的元素进行计数,并 ...

  7. jdk13快来了,jdk8的这几点应该看看!

    说明 jdk8虽然出现很久了,但是可能我们还是有很多人并不太熟悉,本文主要就是介绍说明一些jdk8相关的内容. 主要会讲解: lambda表达式 方法引用 默认方法 Stream 用Optional取 ...

  8. 牛客小白赛4 A 三角形 数学

    链接:https://www.nowcoder.com/acm/contest/134/A来源:牛客网 题目描述 铁子从森林里收集了n根木棍,她开始将它们按顺序的排成一排,从左到右依次为1到n,她回想 ...

  9. codeforces 764 C. Timofey and a tree(dfs+思维)

    题目链接:http://codeforces.com/contest/764/problem/C 题意:给出一个树,然后各个节点有对应的颜色,问是否存在以一个点为根节点子树的颜色都一样. 这里的子树颜 ...

  10. 阿里短信封装SDK TP3.2

    1.阿里短信接口需要企业认证: 2.短信需要短信模板 <?php /** * 阿里云短信验证码发送类 * @param string $accessKeyId key * @param stri ...