原文出处: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的更多相关文章

  1. 导出网页中的table到excel

    导出网页中的table到excel的两种简便方法: 1. 纯 JavaScript 方法,缺点只支持IE浏览器 var elTable = document.getElementById(" ...

  2. Word, PPT和Excel的常用技巧(持续更新)

    本文的目的是记录平时使用Word, PowerPoint和Excel的过程中的一些小技巧,用于提升工作效率. 此文会不定期的更新,更新频率完全取决于实际使用遇到的问题的次数. 目录 Word Powe ...

  3. 使用C#动态生成Word文档/Excel文档的程序测试通过后,部署到IIS服务器上,不能正常使用的问题解决方案

    使用C#动态生成Word文档/Excel文档的程序功能调试.测试通过后,部署到服务器上,不能正常使用的问题解决方案: 原因: 可能asp.net程序或iis访问excel组件时权限不够(Ps:Syst ...

  4. <转>HTML中的table转为excel

    转换html 中的table 为excel,firefox浏览器支持,代码如下 <%@ page language="java" contentType="text ...

  5. 支持IE,FireFox,Chrome三大主流浏览器,通过js+Flash方式将table导出Excel文件

    今天在做项目的时候,遇到了前端下载Excel的功能,结果原先的代码,如下: function generate_excel(tableid) {        var table = document ...

  6. Html table 实现Excel多格粘贴

    Html table 实现Excel多格粘贴 电商网站的后台总少不了各种繁杂数据的录入,旁边的运营妹子录完第138条商品的时候,终于忍不住转身吼到:为什么后台的录入表不能像Excel那样多行粘贴!!! ...

  7. js实现table导出Excel,保留table样式

    浏览器环境:谷歌浏览器 1.在导出Excel的时候,保存table的样式,有2种方法,①是在table的行内写style样式,②是在模板里面添加样式 2.第一种方式:行内添加样式 <td sty ...

  8. 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; ...

  9. ASP如何将table导出EXCEL表格

    网页导出excel表格非常常用,对于一些加载<table>的数据网页,经常会用到这种功能,下面和大家分享一下ASP如何导出EXCEL表格 工具/原料   ASP编辑器 方法/步骤     ...

随机推荐

  1. 将vmware虚拟机转换成qcow2格式的方法

    将vmware虚拟机转换成qcow2格式的方法 http://blog.51cto.com/13570993/2074071 关于qemu安装出现的问题 1.配置qemu是出现can't find p ...

  2. 信息安全之路-web-xss学习(3)

    DOM型xss DOM型xss属于在客户端执行的xss,并不经过服务端解析.测试过程如下 Low型: 源代码: <script> if (document.location.href.in ...

  3. 1、docker容器技术基础入门

    Docker和传统虚拟机的区别               参考文章: https://lwn.net/Articles/531114/    操作中的命名空间详解 https://blog.yadu ...

  4. 前后端分离之【接口文档管理及数据模拟工具docdoc与dochelper】

    前后端分离的常见开发方式是: 后端:接收http请求->根据请求url及params处理对应业务逻辑->将处理结果序列化为json返回 前端:发起http请求并传递相关参数->获取返 ...

  5. [转]osgconv工具简介

    osgconv是一种用来读取3D数据库以及对它们实施一些简单的操作的实用应用程序,同时也被称作 一种专用3D数据库工具. 用osgconv把其他格式的文件转换为OSG所支持的格式 osgconv是一种 ...

  6. PHP 如何获取客户端ip地址

    PHP 如何获取客户端ip地址 一.总结 一句话总结:主要是使用$_SERVER的 REMOTE_ADDR 和 HTTP_X_FORWARDED_FOR 两个属性,在用户使用不同代理的时候这两个属性可 ...

  7. Nginx 常用配置

    Nginx的负载均衡方式 1.轮询(默认) 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除. 2.weight 指定轮询几率,weight和访问比率成正比,用于后端 ...

  8. Python字符串 --Python3

    Python语言中,字符串是用两个双引号或者单引号括起来的词汇表或多个字符. 1.Python字符串的两种序号体系 反向递减序号:-- -9 -8 -7 -6 -5 -4 -3 -2 -1 正向递增序 ...

  9. java之JVM(二)

  10. [转]pycharm 2016.2注册码

    在网上找了好多都不行,最后还是这个好使.在网上搜索了半天挨个试过来最终找到了License server的方法,由此分享给大家.这个也完全没有使用时间的限制~ 直接打开pycharm,选License ...