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编辑器 方法/步骤 ...
随机推荐
- linux启动httpd服务出现 Could not reliably determine the server`s fully qualified domain name.
安装好apache启动httpd服务时,出现httpd: Could not reliably determine the server's fully qualified domain name, ...
- select样式重置
div{ //用div的样式代替select的样式 width: 200px; ...
- pip安装报错
ERROR: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat) python通过pip或者源码来安装某些模块时,这 ...
- 让小乌龟可以唱歌——对Python turtle进行拓展
在Scratch中,小猫是可以唱歌的,而且Scratch的声音木块有着丰富的功能,在这方面Python turtle略有欠缺,今天我们就来完善一下. Python声音模块 Python处理声音的模块很 ...
- vue history模式
注意: 1.前端:config.js路径问题 2.后台:配置nginx
- 用Spark完成复杂TopN计算的两种逻辑
如果有商品品类的数据pairRDD(categoryId,clickCount_orderCount_payCount),用Spark完成Top5,你会怎么做? 这里假设使用Java语言进行编写,那么 ...
- 使用http服务提供yum源
1.安装httpd yum -y install httpd systemctl start httpd systemctl enable httpd 2.镜像资源目录拷贝至http的网站根目录 /v ...
- HBase表数据的转移之使用自定义MapReduce
目标:将fruit表中的一部分数据,通过MR迁入到fruit_mr表中 Step1.构建ReadFruitMapper类,用于读取fruit表中的数据 package com.z.hbase_mr; ...
- Vue-CLI3.0版本配置BootStrap的方法
一.引入jquery bootstrap popper 用 cnpm install jquery bootstrap@3 popper.js --save 用cnpm 来导入 用npm会出 ...
- xadmin邮箱验证码 标题 EmailVerifyRecord object
[修改users-models模块] 1.如果这样不生效 def __unicode__(self): return '{0}({1})'.format(self.code, self.email) ...