-
Notifications
You must be signed in to change notification settings - Fork 56
ES-262901-How to convert word file to excel file by extract table data from a Word document and add those data into a worksheet #533
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
Tables/Extract-Table-to-DataTable/.NET/Extract-Table-to-DataTable.sln
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| | ||
| Microsoft Visual Studio Solution File, Format Version 12.00 | ||
| # Visual Studio Version 17 | ||
| VisualStudioVersion = 17.14.36930.0 d17.14 | ||
| MinimumVisualStudioVersion = 10.0.40219.1 | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Extract-Table-to-DataTable", "Extract-Table-to-DataTable\Extract-Table-to-DataTable.csproj", "{109F9D9A-2486-6191-E3ED-B9C89550B0D4}" | ||
| EndProject | ||
| Global | ||
| GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
| Debug|Any CPU = Debug|Any CPU | ||
| Release|Any CPU = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
| {109F9D9A-2486-6191-E3ED-B9C89550B0D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {109F9D9A-2486-6191-E3ED-B9C89550B0D4}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {109F9D9A-2486-6191-E3ED-B9C89550B0D4}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {109F9D9A-2486-6191-E3ED-B9C89550B0D4}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(SolutionProperties) = preSolution | ||
| HideSolutionNode = FALSE | ||
| EndGlobalSection | ||
| GlobalSection(ExtensibilityGlobals) = postSolution | ||
| SolutionGuid = {8D7007A5-9202-4A9B-A8E2-50EAB025B312} | ||
| EndGlobalSection | ||
| EndGlobal |
Binary file added
BIN
+122 KB
Tables/Extract-Table-to-DataTable/.NET/Extract-Table-to-DataTable/Data/Input.docx
Binary file not shown.
24 changes: 24 additions & 0 deletions
24
...ract-Table-to-DataTable/.NET/Extract-Table-to-DataTable/Extract-Table-to-DataTable.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <RootNamespace>Extract-Table-to-DataTable</RootNamespace> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" /> | ||
| <PackageReference Include="Syncfusion.XlsIO.Net.Core" Version="*" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <None Update="Data\Input.docx"> | ||
| <CopyToOutputDirectory>Always</CopyToOutputDirectory> | ||
| </None> | ||
| <None Update="Output\.gitkeep"> | ||
| <CopyToOutputDirectory>Always</CopyToOutputDirectory> | ||
| </None> | ||
| </ItemGroup> | ||
| </Project> |
1 change: 1 addition & 0 deletions
1
Tables/Extract-Table-to-DataTable/.NET/Extract-Table-to-DataTable/Output/.gitkeep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| |
Binary file added
BIN
+8.5 KB
Tables/Extract-Table-to-DataTable/.NET/Extract-Table-to-DataTable/Output/Result.xlsx
Binary file not shown.
182 changes: 182 additions & 0 deletions
182
Tables/Extract-Table-to-DataTable/.NET/Extract-Table-to-DataTable/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| using System.Text; | ||
| using Syncfusion.DocIO; | ||
| using Syncfusion.DocIO.DLS; | ||
| using Syncfusion.XlsIO; | ||
|
|
||
| class Program | ||
| { | ||
| static void Main(string[] args) | ||
| { | ||
| // Load existing word document | ||
| using (FileStream inputfileStream = new FileStream(Path.GetFullPath(@"../../../Data/Input.docx"), FileMode.Open)) | ||
| { | ||
| using (WordDocument document = new WordDocument(inputfileStream, FormatType.Automatic)) | ||
| { | ||
| using (ExcelEngine engine = new ExcelEngine()) | ||
| { | ||
| IApplication app = engine.Excel; | ||
| app.DefaultVersion = ExcelVersion.Excel2016; | ||
|
|
||
| // Create one sheet to start with; we’ll add sheets as we find more tables. | ||
| IWorkbook workbook = app.Workbooks.Create(1); | ||
| int sheetIndex = 0; | ||
| int tableNumber = 0; | ||
|
|
||
| // Get table entities in word document | ||
| List<Entity> entities = document.FindAllItemsByProperty(EntityType.Table, null, null); | ||
|
|
||
| foreach (Entity entity in entities) | ||
| { | ||
| WTable wTable = (WTable)entity; | ||
|
|
||
| if (sheetIndex >= workbook.Worksheets.Count) | ||
| workbook.Worksheets.Create(); | ||
|
|
||
| IWorksheet worksheet = workbook.Worksheets[sheetIndex++]; | ||
| worksheet.Name = $"Table{++tableNumber}"; | ||
|
|
||
| // Export with merges starting | ||
| ExportWordTableToExcelMerged(wTable, worksheet); | ||
|
|
||
| // Formatting | ||
| worksheet.UsedRange.AutofitRows(); | ||
| worksheet.UsedRange.AutofitColumns(); | ||
| } | ||
| using (FileStream outputStream = new FileStream(Path.GetFullPath(@"../../../Output/Result.xlsx"), FileMode.Create)) | ||
| { | ||
| workbook.SaveAs(outputStream); | ||
| } | ||
| workbook.Close(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes a Word table to the worksheet, preserving horizontal and vertical merges. | ||
| /// startRow/startCol are 1-based Excel coordinates where the table should be placed. | ||
| /// </summary> | ||
| static void ExportWordTableToExcelMerged(IWTable table, IWorksheet worksheet) | ||
| { | ||
| for (int r = 0; r < table.Rows.Count; r++) | ||
| { | ||
| WTableRow wRow = (WTableRow)table.Rows[r]; | ||
|
|
||
| // Map Word's logical grid to Excel columns using GridSpan | ||
| int gridCol = 1; | ||
|
|
||
| for (int i = 0; i < wRow.Cells.Count; i++) | ||
| { | ||
| WTableCell wCell = wRow.Cells[i]; | ||
|
|
||
| // Horizontal width in grid columns | ||
| int hSpan = (int)wCell.GridSpan; | ||
|
|
||
| // Merge flags | ||
| CellMerge vFlag = wCell.CellFormat.VerticalMerge; // None | Start | Continue | ||
| CellMerge hFlag = wCell.CellFormat.HorizontalMerge; | ||
|
|
||
| // Excel start cell for this Word cell | ||
| int xRow = r + 1; | ||
| int excelStartColIndex = gridCol; | ||
|
|
||
| // Compute vertical span when this cell is the START of a vertical merge | ||
| int vSpan = 1; | ||
| if (vFlag == CellMerge.Start) | ||
| { | ||
| // Count how many subsequent rows continue the merge at the same grid column | ||
| for (int nr = r + 1; nr < table.Rows.Count; nr++) | ||
| { | ||
| WTableRow nextRow = (WTableRow)table.Rows[nr]; | ||
| WTableCell nextCell = GetCellAtGridColumn(nextRow, excelStartColIndex); // 1-based grid col | ||
| if (nextCell != null && nextCell.CellFormat.VerticalMerge == CellMerge.Continue) | ||
| vSpan++; | ||
| else | ||
| break; | ||
| } | ||
| } | ||
| if (hFlag == CellMerge.Start) | ||
| { | ||
| for( int nc = i + 1; nc < wRow.Cells.Count; nc++) | ||
| { | ||
| WTableCell cell = wRow.Cells[nc]; | ||
| if (cell != null && cell.CellFormat.HorizontalMerge == CellMerge.Continue) | ||
| hSpan += cell.GridSpan; | ||
| else | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| // Is Start or None of a merge region | ||
| bool isCotinued = | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. isNotContinuedCell |
||
| (vFlag != CellMerge.Continue) && | ||
| (hFlag != CellMerge.Continue); | ||
|
|
||
| if (isCotinued) | ||
| { | ||
| int vMergeEndIndex = xRow + vSpan - 1; | ||
| int hMergeEndColIndex = excelStartColIndex + hSpan - 1; | ||
|
|
||
| // Merge in Excel if region spans multiple cells | ||
| if (vMergeEndIndex > xRow || hMergeEndColIndex > excelStartColIndex) | ||
| worksheet.Range[xRow, excelStartColIndex, vMergeEndIndex, hMergeEndColIndex].Merge(); | ||
|
|
||
| // Write the visible text to the top-left Excel cell | ||
| IRange range = worksheet.Range[xRow, excelStartColIndex]; | ||
| range.Text = BuildCellText(wCell); | ||
|
|
||
| // Format styling | ||
| range.CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter; | ||
| range.CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter; | ||
|
|
||
| worksheet.Range[xRow, excelStartColIndex, vMergeEndIndex, hMergeEndColIndex].CellStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle = ExcelLineStyle.Thin; | ||
| worksheet.Range[xRow, excelStartColIndex, vMergeEndIndex, hMergeEndColIndex].CellStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin; | ||
| worksheet.Range[xRow, excelStartColIndex, vMergeEndIndex, hMergeEndColIndex].CellStyle.Borders[ExcelBordersIndex.EdgeTop].LineStyle = ExcelLineStyle.Thin; | ||
| worksheet.Range[xRow, excelStartColIndex, vMergeEndIndex, hMergeEndColIndex].CellStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin; | ||
|
|
||
| } | ||
|
|
||
| // Advance Excel column cursor by the horizontal span of this Word cell | ||
| gridCol += hSpan; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Returns the WTableCell occupying the given 1-based "grid column" in this row, | ||
| /// taking each cell's GridSpan into account. | ||
| /// </summary> | ||
| static WTableCell GetCellAtGridColumn(WTableRow row, int gridColumn) | ||
| { | ||
| int cursor = 1; // 1-based grid column within the table | ||
| foreach (WTableCell c in row.Cells) | ||
| { | ||
| int span = (int)c.GridSpan; | ||
| int start = cursor; | ||
| int end = cursor + span - 1; | ||
| if (gridColumn >= start && gridColumn <= end) | ||
| return c; | ||
| cursor += span; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Concatenate all paragraph texts in a Word cell (one per line). | ||
| /// </summary> | ||
| static string BuildCellText(WTableCell cell) | ||
| { | ||
| StringBuilder sb = new StringBuilder(); | ||
| for (int p = 0; p < cell.Paragraphs.Count; p++) | ||
| { | ||
| WParagraph para = cell.Paragraphs[p]; | ||
| string text = para.Text?.TrimEnd(); | ||
| if (!string.IsNullOrEmpty(text)) | ||
| { | ||
| if (sb.Length > 0) sb.AppendLine(); | ||
| sb.Append(text); | ||
| } | ||
| } | ||
| return sb.ToString(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls change name