这里向大家介绍一种读取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. 理解Java反射机制

    理解Java反射机制 转载请注明出处,谢谢! 一.Java反射简介 什么是反射? Java的反射机制是Java特性之一,反射机制是构建框架技术的基础所在.灵活掌握Java反射机制,对学习框架技术有很大 ...

  2. MSIL实用指南-this的生成

    C#关键字是非静态方法体内部,用Ldarg_0指代this例子ilGenerator.Emit(OpCodes.Ldarg_0);

  3. 技术改变生活| 免费看VIP视频,屏蔽广告,解锁新姿势!

    说到这个,我就忍不住的要介绍一下今天的主角 Tampermonkey 了.Tampermonkey 是一款免费的浏览器扩展和最为流行的用户脚本管理器,它适用于Chrome, Microsoft Edg ...

  4. python入门(六)二次编码与文件操作

    二次编码 密码本: ascii -- 没有中文 英文1字节 gbk -- 英文 8b(位) 1B(字节) 中文 16b 2B unicode -- 英文32b 4B 中文32b 4B utf-8 -- ...

  5. Keras(四)CNN 卷积神经网络 RNN 循环神经网络 原理及实例

    CNN 卷积神经网络 卷积 池化 https://www.cnblogs.com/peng8098/p/nlp_16.html 中有介绍 以数据集MNIST构建一个卷积神经网路 from keras. ...

  6. HDU - 4370 0 or 1 最短路

    HDU - 4370 参考:https://www.cnblogs.com/hollowstory/p/5670128.html 题意: 给定一个矩阵C, 构造一个A矩阵,满足条件: 1.X12+X1 ...

  7. 模板汇总——splay

    #define lch(x) tr[x].son[0] #define rch(x) tr[x].son[1] ; , root; struct Node{ ], pre, sz; void init ...

  8. bzoj 1146 网络管理Network (CDQ 整体二分 + 树刨)

    题目传送门 题意:求树上路径可修改的第k大值是多少. 题解:CDQ整体二分+树刨. 每一个位置上的数都会有一段持续区间 根据CDQ拆的思维,可以将这个数拆成出现的时间点和消失的时间点. 然后通过整体二 ...

  9. Codefroces 366 C Dima and Salad(dp)

    Dima and Salad 题意:一共有n种水果,每种水果都有一个ai, bi,现求一个最大的ai总和,使得ai之和/对应的bi之和的值等于K. 题解:将bi转换成偏移量,只要偏移到起点位置,就代表 ...

  10. R:ggplot2数据可视化——进阶(1)

    ,分为三个部分,此篇为Part1,推荐学习一些基础知识后阅读~ Part 1: Introduction to ggplot2, 覆盖构建简单图表并进行修饰的基础知识 Part 2: Customiz ...