Convert CSV to DataTable & Paste Values in Word Table using C# .NET | Import CSV then Paste Data into Word Document

Hello everyone

Im totally new to this so please excuse my basic question. I’m looking for a bit of guidance to do the following and wanted to know if is possible. I need to do the following

  • Import a CSV file
  • then paste the csv data into word

Any relevant information or documentation, tips or advice is much appreciated.

PS - I’m using C#

thanks

@taherkhan,

Yes, it seems possible. But, to ensure a timely and accurate response, please ZIP and attach the following resources here for testing:

  • Your simplified input Word document (you want to paste data in)
  • The sample CSV file that you want to import
  • Your expected DOCX document showing the desired output. You can create this document by using MS Word.

As soon as you get these pieces of information ready, we will start investigation into your scenario and provide you code to achieve the same expected output by using Aspose.Total for .NET APIs.

@taherkhan,

Please first convert CSV file into a DataTable object by using the following C# Code of Aspose.Cells for .NET API:

var workbook = new Workbook("E:\\Temp\\sample\\AllVmResources.csv", new Aspose.Cells.TxtLoadOptions { Separator = ',' });
var worksheet = workbook.Worksheets[workbook.Worksheets.ActiveSheetIndex];
DataTable dataTable = worksheet.Cells.ExportDataTable(0, 0,
                                            worksheet.Cells.MaxRow + 1,
                                            worksheet.Cells.MaxColumn + 1,
                                            new ExportTableOptions() { ExportColumnName = true });

Then use the following code of Aspose.Words for .NET API to populate the last Table in your Word document with the DataTable values:

Document doc = new Document("E:\\Temp\\sample\\sampleWordTemplate.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

Table lastTable = doc.LastSection.Body.Tables[2];

Aspose.Words.Tables.Row emptyRow = (Aspose.Words.Tables.Row)lastTable.LastRow.Clone(true);
foreach (Run run in emptyRow.GetChildNodes(NodeType.Run, true))
    run.Text = "";

for (int i = 1; i < dataTable.Rows.Count; i++)
{
    Aspose.Words.Tables.Row newRow = (Aspose.Words.Tables.Row)emptyRow.Clone(true);
    lastTable.Rows.Add(newRow);

    builder.MoveTo(newRow.Cells[1].FirstParagraph.Runs[0]);
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
    builder.Write(dataTable.Rows[i][0].ToString());

    builder.MoveTo(newRow.Cells[2].FirstParagraph.Runs[0]);
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
    builder.Write(dataTable.Rows[i][1].ToString());

    builder.MoveTo(newRow.Cells[3].FirstParagraph.Runs[0]);
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
    builder.Write(dataTable.Rows[i][1].ToString());
}

doc.Save("E:\\Temp\\sample\\20.6.docx");

I have attached the final Word document (20.6.zip (38.8 KB)) here for your reference.