How to convert Word table into Excel using OpenXML
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();
}
}
///
/// This method reads the contents of table using openxml sdk
///
///
///
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().First();
Liststring>> totalRows = new Liststring>>();
int maxCol = 0;
foreach (TableRow row in myTable.Elements())
{
List<string> tempRowValues = new List<string>();
foreach (TableCell cell in row.Elements())
{
tempRowValues.Add(cell.InnerText);
}
maxCol = ProcessList(tempRowValues, totalRows, maxCol);
}
table = ConvertListListStringToDataTable(totalRows, maxCol);
}
return table;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
///
/// Add each row to the totalRows.
///
///
///
/// the max column number in rows of the totalRows
///
private static int ProcessList(List<string> tempRows, Liststring>> totalRows, int MaxCol)
{
if (tempRows.Count > MaxCol)
{
MaxCol = tempRows.Count;
}
totalRows.Add(tempRows);
return MaxCol;
}
///
/// This method converts list data to a data table
///
///
///
/// returns datatable object
private static DataTable ConvertListListStringToDataTable(Liststring>> totalRows, int maxCol)
{
DataTable table = new DataTable();
for (int i = 0; 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;
}
///
/// This method exports datatable to a excel file
///
/// DataTable
/// Excel file name
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.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
SheetData data = worksheetPart.Worksheet.GetFirstChild();
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)1;
foreach (DataColumn column in table.Columns)
{
Cell headerCell = createTextCell(
table.Columns.IndexOf(column) + 1,
1,
column.ColumnName);
header.AppendChild(headerCell);
}
data.AppendChild(header);
//loop through each data row
DataRow contentRow;
for (int i = 0; i < table.Rows.Count; i++)
{
contentRow = table.Rows[i];
data.AppendChild(createContentRow(contentRow, i + 2));
}
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
///
/// This method creates text cell
///
///
///
///
///
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;
}
///
/// This method creates content row
///
///
///
///
private static Row createContentRow( DataRow dataRow, int rowIndex)
{
Row row = new Row
{
RowIndex = (UInt32)rowIndex
};
for (int i = 0; i < dataRow.Table.Columns.Count; i++)
{
Cell dataCell = createTextCell(i + 1, rowIndex, dataRow[i]);
row.AppendChild(dataCell);
}
return row;
}
///
/// Formates or gets column name
///
///
///
private static string getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier;
while (dividend > 0)
{
modifier = (dividend - 1) % 26;
columnName =
Convert.ToChar(65 + modifier).ToString() + columnName;
dividend = (int)((dividend - modifier) / 26);
}
return columnName;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.