/// <summary>
/// 其于OpenXml SDK写的帮助类
/// </summary>
public static class OpenXmlHelper
{
/// <summary>
/// 单元格样式
/// </summary>
public static uint CellStyleIndex { get; set; } /// <summary>
/// 删除sheet
/// </summary>
/// <param name="fileName"></param>
/// <param name="sheetToDelete"></param>
/// <returns></returns>
public static bool XLDeleteSheet(string fileName, string sheetToDelete)
{
bool returnValue = false;
using (SpreadsheetDocument xlDoc = SpreadsheetDocument.Open(fileName, true))
{
XmlDocument doc = new XmlDocument();
doc.Load(xlDoc.WorkbookPart.GetStream()); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("d", doc.DocumentElement.NamespaceURI); string searchString = string.Format("//d:sheet[@name='{0}']", sheetToDelete);
XmlNode node = doc.SelectSingleNode(searchString, nsManager);
if (node != null)
{
XmlAttribute relationAttribute = node.Attributes["r:id"];
if (relationAttribute != null)
{
string relId = relationAttribute.Value;
xlDoc.WorkbookPart.DeletePart(relId);
node.ParentNode.RemoveChild(node);
doc.Save(xlDoc.WorkbookPart.GetStream(FileMode.Create));
returnValue = true;
}
}
}
return returnValue;
} /// <summary>
/// 获取Worksheet
/// </summary>
/// <param name="document">document对象</param>
/// <param name="sheetName">sheetName可空</param>
/// <returns>Worksheet对象</returns>
public static Worksheet GetWorksheet(this SpreadsheetDocument document, string sheetName = null)
{
var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
var sheet = (sheetName == null
? sheets.FirstOrDefault()
: sheets.FirstOrDefault(s => s.Name == sheetName)) ?? sheets.FirstOrDefault(); var worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
return worksheetPart.Worksheet;
}
/// <summary>
/// 获取第一个SheetData
/// </summary>
/// <param name="document">SpreadsheetDocument对象</param>
/// <param name="sheetName">sheetName可为空</param>
/// <returns>SheetData对象</returns>
public static SheetData GetFirstSheetData(this SpreadsheetDocument document, string sheetName = null)
{
return document.GetWorksheet(sheetName).GetFirstChild<SheetData>();
} /// <summary>
/// 获取第一个SheetData
/// </summary>
/// <param name="worksheet">Worksheet对象</param>
/// <returns>SheetData对象</returns>
public static SheetData GetFirstSheetData(this Worksheet worksheet)
{
return worksheet.GetFirstChild<SheetData>();
} /// <summary>
/// 获了共享字符的表格对象
/// </summary>
/// <param name="document">SpreadsheetDocument</param>
/// <returns>SharedStringTablePart对角</returns>
public static SharedStringTablePart GetSharedStringTable(this SpreadsheetDocument document)
{
var sharedStringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
return sharedStringTable;
} /// <summary>
/// 修改单元格的内容.
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
public static void UpdateCellText(this SheetData sheetData, string cellName, string cellText)
{
var cell = sheetData.GetCell(cellName);
if (cell == null)
{
return;
}
cell.UpdateCellText(cellText);
} /// <summary>
/// 设置单元格的值.
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
public static void SetCellValue(this SheetData sheetData, string cellName, object cellText = null)
{
SetCellValue(sheetData, cellName, cellText ?? string.Empty, CellStyleIndex);
} /// <summary>
/// 添加一个单元格
/// </summary>
/// <param name="row">Row对象</param>
/// <param name="cellName">单元格名称</param>
/// <param name="cellText">单元格文本</param>
/// <param name="cellStyleIndex">样式</param>
private static void CreateCell(this Row row, string cellName, object cellText, uint cellStyleIndex)
{
var refCell =
row.Elements<Cell>()
.FirstOrDefault(
cell =>
string.Compare(cell.CellReference.Value, cellName, StringComparison.OrdinalIgnoreCase) > );
var resultCell = new Cell { CellReference = cellName };
resultCell.UpdateCell(cellText, cellStyleIndex);
row.InsertBefore(resultCell, refCell);
}
/// <summary>
/// 设置单元格的值.
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
/// <param name="cellStyleIndex">
/// The cell style index.
/// </param>
private static void SetCellValue(this SheetData sheetData, string cellName, object cellText, uint cellStyleIndex)
{
uint rowIndex = GetRowIndex(cellName);
var row = sheetData.GetRow(rowIndex);
if (row == null)
{
row = new Row { RowIndex = rowIndex };
row.CreateCell(cellName, cellText, cellStyleIndex);
sheetData.Append(row);
}
else
{
var cell = row.GetCell(cellName);
if (cell == null)
{
row.CreateCell(cellName, cellText, cellStyleIndex);
}
else
{
cell.UpdateCell(cellText, cellStyleIndex);
}
}
} /// <summary>
/// The get rows count.
/// </summary>
/// <param name="rows">
/// The rows.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public static int GetRowsCount(this IEnumerable<Row> rows)
{
return rows.GroupBy(x => x.RowIndex.Value).Count();
} /// <summary>
/// 根据行索引获取单元
/// </summary>
/// <param name="rows">
/// The rows.
/// </param>
/// <param name="rowIndex">
/// The row index.
/// </param>
/// <returns>
/// Cell集合
/// </returns>
public static IList<Cell> GetCells(this IEnumerable<Row> rows, int rowIndex)
{
return rows.Where(row => row.RowIndex.Value == rowIndex).SelectMany(row => row.Elements<Cell>()).ToList();
} /// <summary>
/// 获取单元格值
/// </summary>
/// <param name="cells">
/// The cells.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="stringTablePart">
/// The string table part.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string GetCellValue(this IEnumerable<Cell> cells, string cellName, SharedStringTablePart stringTablePart)
{
if (cells == null)
{
throw new ArgumentNullException("cells");
}
if (cellName == null)
{
throw new ArgumentNullException("cellName");
}
var cell = (from item in cells where item.CellReference == cellName select item).FirstOrDefault();
if (cell == null)
{
return string.Empty;
}
if (cell.ChildElements.Count == )
{
return string.Empty;
}
var value = cell.CellValue.InnerText;
if (cell.DataType == null)
{
return value;
}
switch (cell.DataType.Value)
{
case CellValues.SharedString:
if (stringTablePart != null)
{
value = stringTablePart.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
value = value == "" ? "FALSE" : "TRUE";
break;
}
return value;
} /// <summary>
/// 验证文档
/// </summary>
/// <param name="document">
/// The document.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string ValidateDocument(this SpreadsheetDocument document)
{
var msg = new StringBuilder();
try
{
var validator = new OpenXmlValidator();
int count = ;
foreach (ValidationErrorInfo error in validator.Validate(document))
{
count++;
msg.Append("\nError " + count)
.Append("\nDescription: " + error.Description)
.Append("\nErrorType: " + error.ErrorType)
.Append("\nNode: " + error.Node)
.Append("\nPath: " + error.Path.XPath)
.Append("\nPart: " + error.Part.Uri)
.Append("\n-------------------------------------------");
}
}
catch (Exception ex)
{
msg.Append(ex.Message);
} return msg.ToString();
} /// <summary>
/// 根据单元格名称获取行索引.
/// </summary>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <returns>
/// The <see cref="uint"/>.
/// </returns>
private static uint GetRowIndex(string cellName)
{
var regex = new Regex(@"\d+");
var match = regex.Match(cellName);
return uint.Parse(match.Value);
} /// <summary>
/// The get cell data type.
/// </summary>
/// <param name="cellText">
/// The cell text.
/// </param>
/// <returns>
/// The <see cref="CellValues"/>.
/// </returns>
private static CellValues GetCellDataType(object cellText)
{
var type = cellText.GetType();
switch (type.Name)
{
case "Int32":
case "Decimal":
case "Double":
case "Int64":
return CellValues.Number;
case "String":
return CellValues.String;
//// case "DateTime":
//// return CellValues.Date;
default:
return CellValues.String;
}
} /// <summary>
/// 修改单元格内容(文本、样式)
/// </summary>
/// <param name="cell">
/// The cell.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
/// <param name="cellStyleIndex">
/// The cell style index.
/// </param>
private static void UpdateCell(this Cell cell, object cellText, uint cellStyleIndex)
{
cell.UpdateCellText(cellText);
cell.StyleIndex = cellStyleIndex;
} /// <summary>
/// 修改单元格的文本
/// </summary>
/// <param name="cell">Cell对象</param>
/// <param name="cellText">文本字符串</param>
private static void UpdateCellText(this Cell cell, object cellText)
{
cell.DataType = GetCellDataType(cellText);
cell.CellValue = cell.CellValue ?? new CellValue();
cell.CellValue.Text = cellText.ToString();
} /// <summary>
/// 获取行
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="rowIndex">
/// The row index.
/// </param>
/// <returns>
/// The <see cref="Row"/>.
/// </returns>
private static Row GetRow(this SheetData sheetData, long rowIndex)
{
return sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
} /// <summary>
/// 获取单元格
/// </summary>
/// <param name="row">
/// The row.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <returns>
/// The <see cref="Cell"/>.
/// </returns>
private static Cell GetCell(this Row row, string cellName)
{
return row.Elements<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
} /// <summary>
/// 获取单元格
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <returns>
/// The <see cref="Cell"/>.
/// </returns>
private static Cell GetCell(this SheetData sheetData, string cellName)
{
return sheetData.Descendants<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
}
#region 样式 /*
public static Borders CreateStylesheet()
{
//Stylesheet stylesheet1 = new Stylesheet()
// {
// MCAttributes =
// new MarkupCompatibilityAttributes()
// {
// Ignorable = "x14ac"
// }
// };
//stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
//stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); var borders1 = new Borders(
new Border(
// Index 1 - Applies a Left, Right, Top, Bottom border to a cell
new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new DiagonalBorder())); // stylesheet1.Append(borders1);
// return stylesheet1;
return borders1;
} public static Border CreateBorder()
{
//Stylesheet stylesheet1 = new Stylesheet()
// {
// MCAttributes =
// new MarkupCompatibilityAttributes()
// {
// Ignorable = "x14ac"
// }
// };
//stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
//stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); // var borders1 = new Borders(
return new Border(
// Index 1 - Applies a Left, Right, Top, Bottom border to a cell
new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new DiagonalBorder()); // stylesheet1.Append(borders1);
// return stylesheet1;
// return borders1;
} */
#endregion
}

其于OpenXml SDK写的帮助类的更多相关文章

  1. Open-Xml SDK使用介绍

    Office Open XML 简称为 ooxml ,是Microsoft 在 Office 2007 之后推行的标准格式,用在 Excel, Word, PPT 等文件.已确定为国际标准. Open ...

  2. OpenXml SDK学习笔记(1):Word的基本结构

    能写多少篇我就不确定了,可能就这一篇就太监了,也有可能会写不少. OpenXml SDK 相信很多人都不陌生,这个就是管Office一家的文档格式,Word, Excel, PowerPoint等都用 ...

  3. OpenXml Sdk 根据Word模板导出到word

    一:OpenXml Sdk 简介 Open XML标准的简单介绍:Ecma Office Open XML(“Open XML”)是针对字处理文档.演示文稿和电子表格的国际化开放标准,可免费供多个应用 ...

  4. js 一个自写的 监测类

    自从认识了jQuery后,很多页面加载入口,都放在document.ready里面.但是有时候这个觉得ready加载太慢, 这个[监测类 ]就开始产生了 效果类似这个. 每10毫秒检查一次,直到加载了 ...

  5. Java基础-继承-编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数 loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个 类都有构造方法和输出相关数据的方法。最后,写一个测试类来测试这些类的功 能。

    #29.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight.小车类Car是Vehicle的子类,其中包含的属性有载人数 loader.卡车类T ...

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

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

  7. [Office][C#] NPOI、OpenXML SDK、OpenOffice.org SDK 写入资料到 EXCEL 档案[转]

    原文地址:http://www.dotblogs.com.tw/chou/archive/2010/04/29/14912.aspx 一.簡介 要將資料寫入 EXCEL 檔案有許多的方法,但假如電腦不 ...

  8. ItcastOA_设计BaseDao_设计DAO接口和实现类_写DAO实现类中的方法内容

    3. 基础功能 3.1. 设计BaseDao接口与BaseDaoImpl类 每个实体都应有一个对应的Dao,他封装了对这个实体的数据库操作.例 实体Dao接口实现类 ================= ...

  9. 基于七牛Python SDK写的一个批量下载脚本

    前言 上一篇基于七牛Python SDK写的一个同步脚本所写的脚本只支持上传,不支持文件下载. 虽然这个需求不太强烈,但有可能有人(在备份.迁移时)需要,而官方有没提供对应的工具,所以我就把这个功能也 ...

随机推荐

  1. 字符串String的API

      字符串的理解 1. 字符串的属性 str.length 2. 字符串的方法 charAt() charCodeAt() indexOf() lastIndexOf() slice() substr ...

  2. 一个简单SpringBoot例子

    一:为什么使用springBoot: 有利于开发(整合框架,例如整合了springMVC,Mybatis等框架); 启动无需配置tomcat(java应用程序运行,实际以jar包运行),内置tomca ...

  3. 【HQL】小技巧

    case1.a与b匹配表保留一条匹配关系 背景:匹配b,b匹配a在同一张表: match_table表为: uid,m_uid 111,222 222,111 需求:只保留一条匹配关系. 结果为: u ...

  4. ELK+Beats日志分析系统部署

    一.            名词介绍: E:ElasticSearch 搜索,简称es L:Logstash 管理日志和事件的工具 K:Kibana 功能强大的数据显示客户端 Beats 轻量级数据传 ...

  5. spring 之 property-placeholder 分析

    不难知道, property-placeholder 的解析是 PropertyPlaceholderBeanDefinitionParser 完成的, 但是 它仅仅是个parser , 它仅仅是读取 ...

  6. IVideoWindow 在directshow采集链路中的使用

    dshow中一个完整采集链路一般如下: Capture Device----->SampleGraber ------>Render 如果只要采集原始数据可以不用渲染链路那就如下: Cap ...

  7. MFC---关于string.h相关函数

    1.在VS2005中使用strcpy.strcat.sprintf出现如:mfc中'strcpy' was declared deprecated警告 这是因为VS2005中认为CRT中的一组函数如果 ...

  8. mysql5.5升级到5.7

    一.首先把mysql服务停止,复制mysql5.5中的data文件夹中的内容(你需要的数据库),放在mysql5.7的data文件夹中; 二.启动切换mysql5.7版本,(我这用的是phpwamp, ...

  9. mysql学习笔记--数据操作

    一.插入数据 1. 语法:insert into 表名 (字段名.字段名,...) values (值1,值2...) 2. 注意: a. 插入字段的个数和顺序与值的个数和顺序必须一致 b. 通过de ...

  10. [leetcode]43. Multiply Strings高精度乘法

    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and ...