I’m trying to read a word document using C#. I am able to get all text but I want to be able to read line by line and store in a list and bind to a gridview. Currently my code returns a list of one item only with all text (not line by line as desired). I’m using the Microsoft.Office.Interop.Word library to read the file. Below is my code till now:
Application word = new Application(); Document doc = new Document(); object fileName = path; // Define an object to pass to the API for missing parameters object missing = System.Type.Missing; doc = word.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); String read = string.Empty; List<string> data = new List<string>(); foreach (Range tmpRange in doc.StoryRanges) { //read += tmpRange.Text + "<br>"; data.Add(tmpRange.Text); } ((_Document)doc).Close(); ((_Application)word).Quit(); GridView1.DataSource = data; GridView1.DataBind();
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Ok. I found the solution here.
The final code is as follows:
Application word = new Application(); Document doc = new Document(); object fileName = path; // Define an object to pass to the API for missing parameters object missing = System.Type.Missing; doc = word.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); String read = string.Empty; List<string> data = new List<string>(); for (int i = 0; i < doc.Paragraphs.Count; i++) { string temp = doc.Paragraphs[i + 1].Range.Text.Trim(); if (temp != string.Empty) data.Add(temp); } ((_Document)doc).Close(); ((_Application)word).Quit(); GridView1.DataSource = data; GridView1.DataBind();
Method 2
The above code is correct, but it’s too slow.
I have improved the code, and it’s much faster than the above one.
List<string> data = new List<string>(); Application app = new Application(); Document doc = app.Documents.Open(ref readFromPath); foreach (Paragraph objParagraph in doc.Paragraphs) data.Add(objParagraph.Range.Text.Trim()); ((_Document)doc).Close(); ((_Application)app).Quit();
Method 3
How about this yo. Get all the words from the doc and split them on return or whatever is better for you. Then turn into list
List<string> lines = doc.Content.Text.Split('n').ToList();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0