How to convert Word table into Excel using OpenXML
原文出处:https://code.msdn.microsoft.com/How-to-convert-Word-table-0cb4c9c3
class Program
{
static void Main(string[] args)
{
string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string wordFile = appPath + "\\TestDoc.docx"; DataTable dataTable = ReadWordTable(wordFile); if (dataTable != null)
{
string sFile = appPath + "\\ExportExcel.xlsx"; ExportDataTableToExcel(dataTable, sFile); Console.WriteLine("Contents of word table exported to excel spreadsheet"); Console.ReadKey();
}
} /// <summary>
/// This method reads the contents of table using openxml sdk
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static DataTable ReadWordTable(string fileName)
{
DataTable table; try
{
using (var document = WordprocessingDocument.Open(fileName, false))
{
var docPart = document.MainDocumentPart;
var doc = docPart.Document; DocumentFormat.OpenXml.Wordprocessing.Table myTable = doc.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>().First(); List<List<string>> totalRows = new List<List<string>>();
int maxCol = ; foreach (TableRow row in myTable.Elements<TableRow>())
{
List<string> tempRowValues = new List<string>();
foreach (TableCell cell in row.Elements<TableCell>())
{
tempRowValues.Add(cell.InnerText);
} maxCol = ProcessList(tempRowValues, totalRows, maxCol);
} table = ConvertListListStringToDataTable(totalRows, maxCol);
} return table;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); return null;
}
} /// <summary>
/// Add each row to the totalRows.
/// </summary>
/// <param name="tempRows"></param>
/// <param name="totalRows"></param>
/// <param name="MaxCol">the max column number in rows of the totalRows</param>
/// <returns></returns>
private static int ProcessList(List<string> tempRows, List<List<string>> totalRows, int MaxCol)
{
if (tempRows.Count > MaxCol)
{
MaxCol = tempRows.Count;
} totalRows.Add(tempRows);
return MaxCol;
} /// <summary>
/// This method converts list data to a data table
/// </summary>
/// <param name="totalRows"></param>
/// <param name="maxCol"></param>
/// <returns>returns datatable object</returns>
private static DataTable ConvertListListStringToDataTable(List<List<string>> totalRows, int maxCol)
{
DataTable table = new DataTable();
for (int i = ; i < maxCol; i++)
{
table.Columns.Add();
}
foreach (List<string> row in totalRows)
{
while (row.Count < maxCol)
{
row.Add("");
}
table.Rows.Add(row.ToArray());
}
return table;
} /// <summary>
/// This method exports datatable to a excel file
/// </summary>
/// <param name="table">DataTable</param>
/// <param name="exportFile">Excel file name</param>
private static void ExportDataTableToExcel(DataTable table, string exportFile)
{
try
{
// Create a spreadsheet document by supplying the filepath.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(exportFile, 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 = ,
Name = "mySheet"
};
sheets.Append(sheet); SheetData data = worksheetPart.Worksheet.GetFirstChild<SheetData>(); //add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32); foreach (DataColumn column in table.Columns)
{
Cell headerCell = createTextCell(
table.Columns.IndexOf(column) + ,
,
column.ColumnName); header.AppendChild(headerCell);
}
data.AppendChild(header); //loop through each data row
DataRow contentRow;
for (int i = ; i < table.Rows.Count; i++)
{
contentRow = table.Rows[i];
data.AppendChild(createContentRow(contentRow, i + ));
} workbookpart.Workbook.Save(); // Close the document.
spreadsheetDocument.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// This method creates text cell
/// </summary>
/// <param name="columnIndex"></param>
/// <param name="rowIndex"></param>
/// <param name="cellValue"></param>
/// <returns></returns>
private static Cell createTextCell( int columnIndex, int rowIndex, object cellValue)
{
Cell cell = new Cell(); cell.DataType = CellValues.InlineString;
cell.CellReference = getColumnName(columnIndex) + rowIndex; InlineString inlineString = new InlineString();
DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text(); t.Text = cellValue.ToString();
inlineString.AppendChild(t);
cell.AppendChild(inlineString); return cell;
} /// <summary>
/// This method creates content row
/// </summary>
/// <param name="dataRow"></param>
/// <param name="rowIndex"></param>
/// <returns></returns>
private static Row createContentRow( DataRow dataRow, int rowIndex)
{
Row row = new Row
{
RowIndex = (UInt32)rowIndex
}; for (int i = ; i < dataRow.Table.Columns.Count; i++)
{
Cell dataCell = createTextCell(i + , rowIndex, dataRow[i]);
row.AppendChild(dataCell);
}
return row;
} /// <summary>
/// Formates or gets column name
/// </summary>
/// <param name="columnIndex"></param>
/// <returns></returns>
private static string getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier; while (dividend > )
{
modifier = (dividend - ) % ;
columnName =
Convert.ToChar( + modifier).ToString() + columnName;
dividend = (int)((dividend - modifier) / );
} return columnName;
}
}
How to convert Word table into Excel using OpenXML的更多相关文章
- 导出网页中的table到excel
导出网页中的table到excel的两种简便方法: 1. 纯 JavaScript 方法,缺点只支持IE浏览器 var elTable = document.getElementById(" ...
- Word, PPT和Excel的常用技巧(持续更新)
本文的目的是记录平时使用Word, PowerPoint和Excel的过程中的一些小技巧,用于提升工作效率. 此文会不定期的更新,更新频率完全取决于实际使用遇到的问题的次数. 目录 Word Powe ...
- 使用C#动态生成Word文档/Excel文档的程序测试通过后,部署到IIS服务器上,不能正常使用的问题解决方案
使用C#动态生成Word文档/Excel文档的程序功能调试.测试通过后,部署到服务器上,不能正常使用的问题解决方案: 原因: 可能asp.net程序或iis访问excel组件时权限不够(Ps:Syst ...
- <转>HTML中的table转为excel
转换html 中的table 为excel,firefox浏览器支持,代码如下 <%@ page language="java" contentType="text ...
- 支持IE,FireFox,Chrome三大主流浏览器,通过js+Flash方式将table导出Excel文件
今天在做项目的时候,遇到了前端下载Excel的功能,结果原先的代码,如下: function generate_excel(tableid) { var table = document ...
- Html table 实现Excel多格粘贴
Html table 实现Excel多格粘贴 电商网站的后台总少不了各种繁杂数据的录入,旁边的运营妹子录完第138条商品的时候,终于忍不住转身吼到:为什么后台的录入表不能像Excel那样多行粘贴!!! ...
- js实现table导出Excel,保留table样式
浏览器环境:谷歌浏览器 1.在导出Excel的时候,保存table的样式,有2种方法,①是在table的行内写style样式,②是在模板里面添加样式 2.第一种方式:行内添加样式 <td sty ...
- html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式
先上代码 <script type="text/javascript" language="javascript"> var idTmr; ...
- ASP如何将table导出EXCEL表格
网页导出excel表格非常常用,对于一些加载<table>的数据网页,经常会用到这种功能,下面和大家分享一下ASP如何导出EXCEL表格 工具/原料 ASP编辑器 方法/步骤 ...
随机推荐
- 持久层Mybatis3底层源码分析,原理解析
Mybatis-持久层的框架,功能是非常强大的,对于移动互联网的高并发 和 高性能是非常有利的,相对于Hibernate全自动的ORM框架,Mybatis简单,易于学习,sql编写在xml文件中,和代 ...
- GIT命令介绍
Linus花了两周时间自己用C写了一个分布式版本控制系统,这就是Git!一个月之内,Linux系统的源码已经由Git管理了!牛是怎么定义的呢?大家可以体会一下. 区别与集中式的分布式实现!!!! 集中 ...
- Apache Solr入门教程(转)
1.为什么选择Apache Solr Apache Solr是一个功能强大的搜索服务器,它支持REST风格API.Solr是基于Lucene的,Lucene 支持强大的匹配能力,如短语,通配符,连接, ...
- Windows 循环根据进程名称 存在则删除该进程
@echo off:Looptasklist | findstr /i "javaw.exe" >nul 2>nul && (taskkill -f / ...
- Notepad++对比文件
Notepad++怎么对比文件,安装文件对比插件Compare pluginhttps://blog.csdn.net/qq_31772441/article/details/80306265 可以只 ...
- 百度ueditor上传图片时如何设置默认宽高度
百度ueditor上传图片时如何设置默认宽高度 一.总结 一句话总结:直接css或者js里面限制一下就好,可以用html全局限制一下图片的最大高度 直接css或者js里面限制一下就好,可以用html全 ...
- iphone上mitmproxy证书设置
PC端安装mitmproxy并添加证书后,基本问题不大,都能正常运行起来 手机端iphone上下载安装mitmproxy证书: 1.手机和PC在同一个局域网中,设置wifi代理为PC端的ip,端口为m ...
- 使用querybuilder做忽略大小写查询的例子
自定义Predicate: import com.day.cq.search.Predicate; import com.day.cq.search.eval.AbstractPredicateEva ...
- IntelliJ IDEA 2017.3.1安装步骤
https://www.jetbrains.com/idea/download/#section=windows 下载旗舰版 1.下载完成后,运行安装: 2.next: 3.选择你要安装的目录,nex ...
- BUAAOO-First-Summary
目录 homework & class & trainning : 两次上机.三次作业.四周课堂 code analysis & review : 为什么我没有bug 黑盒测试 ...