Core: Read/Write Word Document in .Net Core

Created on 10 Feb 2017  路  7Comments  路  Source: dotnet/core

I want to read and write in word document like header content and second header content

i try to to use

var uploaded = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
ViewData["Message"] = uploaded.ToString();
string FileStreamobj =Path.Combine(uploaded , "POC.doc")
var owners=System.IO.File.ReadAllLines(@"D:\Test\New\WebApplication6\WebApplication6\wwwroot\Dashboard Framework for-CAT and AAA Server.docx");

But Its Not Working

then i try this

using (StreamReader sr = File.OpenText(@"D:\Test\New\WebApplication6\WebApplication6\wwwroot\Dashboard Framework for-CAT and AAA Server.docx"))
{
string tables = null;

        while ((tables = sr.ReadLine()) != null)
          {
               Console.WriteLine("{0}", tables);
          }
           Console.WriteLine("Table Printed.");
       }

But It not working ...

in Asp.net framework they have used Microsoft.Office.Interop.Word but that is not available in .net core

what should i do ?

Plz help me out

@shanselman @AArnott @anurse @AustinWise @devhawk @madskristensen @SajayAntony @mairaw

Most helpful comment

Hi guys, could you please point out to a library able to convert .docx to .pdf on .net core?

All 7 comments

When i am using System.IO.File.ReadAllLines it give me garbage value...

Check out Open-XML-SDK. Specifically, carefully read the "How to install the NuGet package section"; you will need to add a custom package source.

Then you can write something like this:

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using (var doc = WordprocessingDocument.Open(@"d:\AustinWise\Documents\Turtles.docx", false))
            {
                foreach (var el in doc.MainDocumentPart.Document.Body.Elements().OfType<Paragraph>())
                {
                    Console.WriteLine(el.InnerText);
                }
            }
        }
    }
}

The API is not simple, so it might take a while to figure out how to get what you are looking for,

Thank you so much @AustinWise it helps a lot and save my time

one more thing what about .pdf file?

For create, edit and read pdf docs you can use iTextSharp.
Package for .net core:
https://www.nuget.org/packages/iTextSharp.LGPLv2.Core/

thanks a lot @neyromant its work..

Hi guys, could you please point out to a library able to convert .docx to .pdf on .net core?

Was this page helpful?
0 / 5 - 0 ratings