Click to See Complete Forum and Search --> : How to get the wordcount for an Excel document


lalaphil
April 10th, 2008, 05:39 AM
Hi,

Is there an easy way to get the wordcount of an Excel document in C#?

Thanks for your help,

Philippe

lalaphil
April 14th, 2008, 07:10 AM
Hi again,

Is there anyone who could help me on this?

Thanks for your help,

Philippe

Overridden Member
April 14th, 2008, 07:38 AM
mmm.. your request is a bit odd. Count the words in an Excel spreadsheet? But I suppose you have a good reason.

Since Excel was designed to do calculations and present them in a readable form, I don't think there's a specific API in Excel to count words.
One possible route would be to loop over all the cells and count the words "manually".

lalaphil
April 14th, 2008, 08:10 AM
Thanks for your answer, I was hoping something existed :(

I saw that you can save a sheet as a text file. Is there a way to get the content of a sheet directly in a string variable ? something like MyStringVariable = Sheet.text; I couldn't find anything

Thanks for your help,

Philippe

Overridden Member
April 14th, 2008, 08:56 AM
I tried looping over the cells and it was very slow. So don't try that. I think you'd better save it in CSV or similar format, and count the words in that.

edit : I don't think there's an API for reading a complete worksheet in a string.
You could read the entire csv file in 1 string though!

lalaphil
April 14th, 2008, 09:49 AM
Thanks again for your answer, I will save the sheet as a text file and count the words from it.

I made this code:
//save the sheet as a text file
Ws.SaveAs("c:\\Tamp.txt", Microsoft.Office.Interop.Excel.XlFileFormat.xlUnicodeText, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

//open the text file
Reader = new StreamReader(File.OpenRead("c:\\Tamp.txt"), Encoding.Default, true);

//count the words
sContent = Reader.ReadToEnd();
iWordCount=iWordCount + sContent.Split(' ').Length;
Reader.Dispose();


My problem is that I can't read the text file as it hasn't been created yet when I try to open it :(.

Is there a way to wait that the file is created before to read it?
Is there a better way to do this thing?

Thanks for your answer,

Philippe