Editing word table using C#
Hi All,
I want to search a Microsoft Word document from the end and then edit the the first table that is found.To the first table that is found I want to Copy a column on the basis of column heading and then paste the same column(with a different name provided by user) in the same table and Save the documnet.
I want this to be done for all the documents that user selects from a list view containing the path of documents.
PLease guide me so that I can complete this task ASAP.
Note:For all the documents only the last table has to be modified and I want to do this using C# Windows Application.
Thanks
John GlennPosted Mar 1, 2012, 6:19 AM
you can edit Word with C# easily using this C# / VB.NET Word component.
Here is a C# code for your scenario:
{
// Use the component in free mode.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
// Load a document from the file.
var document = DocumentModel.Load(documentName, LoadOptions.DocxDefault);
// Get the last table in the document.
var table = (Table)document.GetChildElements(true, ElementType.Table).LastOrDefault();
// Get source and destination column indices.
int sourceColumnIndex = GetColumnIndex(table, sourceColumnName);
int destinationColumnIndex = GetColumnIndex(table, destinationColumnName);
// For each row, except header row - copy data from source cell to destination cell.
for (int i = 1; i < table.Rows.Count; ++i)
{
var row = table.Rows[i];
var sourceCell = row.Cells[sourceColumnIndex];
var destinationCell = row.Cells[destinationColumnIndex];
destinationCell.Blocks.Clear();
foreach (var block in sourceCell.Blocks)
destinationCell.Blocks.Add(block.Clone(true));
}
// Save the document to a file.
document.Save("Document.docx", SaveOptions.DocxDefault);
// Open a file with Microsoft Word.
Process.Start("Document.docx");
}
// Utility method to get column index from column name.
private static int GetColumnIndex(Table table, string columnName)
{
var headerRow = table.Rows[0];
for (int i = 0; i < headerRow.Cells.Count; ++i)
if (headerRow.Cells[i].Blocks.Cast<Paragraph>(0).Inlines.Cast<Run>(0).Text == columnName)
return i;
return -1;
}
Nir BarPosted Sep 23, 2009, 4:50 AM
Pseudo code of what you need goes something like:
Full documentation (though not complete as one would expect) can be found here:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word%28office.11%29.aspx
Please mark this as answer if it helps you
Nir