Using Microsoft object library you can do many functionalities like creating new document, appending existing document, counting no of lines, size of the document, Spell Check etc....
Required:
This application require to have COM reference to the project, which can be done as:
Right clicking in the solution explorer on References->>Add Reference.
Click on the COM tab and look for the Microsoft Word 11.0 Object Library. Click Select and OK.
You can use the following code in your .cs page as:
This application require to have COM reference to the project, which can be done as:
Right clicking in the solution explorer on References->>Add Reference.
Click on the COM tab and look for the Microsoft Word 11.0 Object Library. Click Select and OK.
You can use the following code in your .cs page as:
- using Microsoft.Office;
- using Microsoft.Office.Interop.Word;
Some of the declarations required in the project are as follows:
- protected Microsoft.Office.Interop.Word.ApplicationClass objWord = new ApplicationClass();
- //This creates new object of Word.ApplicationClass
- protected string strPathToUpload;
- //Path to upload files "Uploaded"
- protected string strPathToConvert;
- //Path to convert uploaded files and save
- object fltDocFormat = 10;
- //For filtered HTML Output
- protected object missing = System.Reflection.Missing.Value;
- //Is just to skeep the parameters which are passed as boject reference, these are seems to be optional parameters
- protected object readOnly = false;
- protected object isVisible = false;
- //The process has to be in invisible mode
- <asp:FileUpload ID="fUpload" runat="server"/> &
- <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
- protected void btnUpload_Click(object sender, EventArgs e)
- {
- //Code to check if user has selected any file on the form
- if (!(fUpload.HasFile))
- {
- lblMessage.Text = "Please choose file to upload";
- }
- else
- {
- try
- {
- //To check the file extension if it is word document or something else
- string strFileName = fUpload.FileName;
- string[] strSep = fUpload.FileName.Split('.');
- int arrLength = strSep.Length - 1;
- string strExt = strSep[arrLength].ToString().ToUpper();
- //Save the uploaded file to the folder
- strPathToUpload = Server.MapPath("Uploaded");
- //Map-path to the folder where html to be saved
- strPathToConvert = Server.MapPath("WordToHtml");
- object FileName = strPathToUpload + "\\" + fUpload.FileName;
- object FileToSave = strPathToConvert + "\\" + fUpload.FileName + ".htm";
- if (strExt.ToUpper().Equals("DOC"))
- {
- fUpload.SaveAs(strPathToUpload + "\\" + fUpload.FileName);
- lblMessage.Text = "File uploaded successfully";
- //open the file internally in word. In the method all the parameters should be passed by object reference
- objWord.Documents.Open(ref FileName, ref readOnly, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing,
- ref missing, ref missing);
- //Do the background activity
- objWord.Visible = false;
- Microsoft.Office.Interop.Word.Document oDoc = objWord.ActiveDocument;
- oDoc.SaveAs(ref FileToSave, ref fltDocFormat, 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);
- lblMessage.Text = fUpload.FileName + " converted to HTML successfully";
- }
- else
- {
- lblMessage.Text = "Invalid file selected!";
- }
- //Close/quit word
- objWord.Quit(ref missing, ref missing, ref missing);
- }
- catch (Exception ex)
- {
- Response.Write(ex.Message);
- }
- }
- }
On some of the machines you need to have "IUSER_MACHINE" rights to upload files to particular folders.

sangram bishiPosted Aug 2, 2013, 5:46 AM
oDoc = objWord.ActiveDocument working in development environment but failed after deploy in IIS 7.5. please help..thanks..
JitendraPosted Jan 21, 2013, 2:17 AM
thanks a lot for sharing such a good code...
JitendraPosted Jan 21, 2013, 2:17 AM
thanks a lot for sharing such a good code...
JitendraPosted Jan 21, 2013, 2:17 AM
thanks a lot for sharing such a good code...
Bill PalanskiPosted Jun 15, 2012, 1:41 PM
Is there anyway to customize the css that it output?
Bill PalanskiPosted Jun 15, 2012, 12:23 PM
Use Word.Application instead of Word.ApplicationClass in 12.0
hassan alrehamyPosted May 10, 2012, 8:09 PM
thank you for this work , I really was in need for such code, I use a long procedure to produce such operation , where I had to extract the code from word to pdf then to flash ... regards , hassan http://www.uobabylon.edu.iq/nt/
hassan alrehamyPosted May 10, 2012, 8:06 PM
Thank you , but how can I display the content of MS Words file into flash paper ? check this problem : http://repository.uobabylon.edu.iq/applied_edition2.aspx
skc cdsPosted Feb 20, 2012, 1:49 AM
Hi, I used the above code, it works fine but some time I am facing an error while opening word document.I am using Microsoft.Word 12.0 Object library. Error - Word encountered an error processing the XML file Temp.docx. Microsoft Office cannot open this file because some parts are missing or invalid. I tried to set Open and Repair to true in objWord.Documents.Open method but it didn't worked.Please suggest.
Srinivasan VPosted Oct 10, 2011, 12:37 AM
This functionality is working in development. But it is not working when the application is deployed in iis 7.0. Kindly let us know any settings has to be modified in IIS to fix this issue
sujith monyPosted Oct 4, 2011, 4:36 PM
hi when i run this code i am getting this error msg,can you help me to solve this one Error 1 Interop type 'Microsoft.Office.Interop.Word.ApplicationClass' cannot be embedded. Use the applicable interface instead. C:\Users\X-SMony\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\Default.aspx.cs 20 46 WebApplication1
shyam morePosted May 30, 2011, 7:43 AM
hi, plz anybody tell me how to convert doc file into HTML file in PHP but without using COM object.?
Anup BhattiPosted Apr 20, 2011, 2:37 AM
HI but here the portion in header and footer is not being copy. Do you have any alternate in which header and footer too can be copied?
Sunita TajanpurePosted Dec 1, 2010, 2:25 AM
Thank you sir for the code...... it works absolutely fine.... my query is ... I am able to convert the word doc to html,If the word doc contains any, while converting it creates one folder for the images and the respective html file.... Now when i display it in my web page the images inside converted html file cannot be found .... I am using IFRAME to show the html file,because I want to show the file directly in the browser
Prokopis PPosted Oct 28, 2010, 12:47 PM
hi i have a question when am doing fileupload.saveas(Server.MapPath(....)) is working ok with no problem and i can see the uploaded document to my server. but when am using the objWord.Documents.Open(ref FileName,....) am getting security exception under a medium trust. can someon please help me about this matter? if di't explain something very well let me know
kin kinPosted Oct 30, 2009, 2:16 PM
i got this error exception : "This command is not available because no document is open." Do someone know the solution to resolve this :(
sarat chandraPosted Sep 19, 2009, 5:26 AM
hi when i try to open this file i got an error can u solve this hope u will respond to this i really nedd this very imp one error: Error 2 Could not load file or assembly 'Microsoft.Office.Interop.Word, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified. C:\Documents and Settings\administrator.MANISIN\Desktop\WordToHtml\Web.Config 31
ajay kumarPosted Jun 15, 2009, 1:14 AM
Hi , I got this error while running the code provide by you Server Error in '/Single_StoreUI' Application. Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005. ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user. To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access. Source Error: Line 13: public partial class WordToHTML : System.Web.UI.Page Line 14: { Line 15: protected Microsoft.Office.Interop.Word.ApplicationClass objWord = new ApplicationClass(); Line 16: protected string strPathToUpload; //Path to upload files "Uploaded" Line 17: protected string strPathToConvert; //Path to convert uploaded files and save Source File: d:\Applications\MartJack\MartJackRevamp\Single_StoreUI\WordToHTML.aspx.cs Line: 15 Stack Trace: [UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005.] WordToHTML..ctor() in d:\Applications\MartJack\MartJackRevamp\Single_StoreUI\WordToHTML.aspx.cs:15 ASP.wordtohtml_aspx..ctor() in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\single_storeui\2c329136\f48c1fef\App_Web_wordtohtml.aspx.cdcab7d2.cz3d2s7d.0.cs:0 __ASP.FastObjectFactory_app_web_wordtohtml_aspx_cdcab7d2_cz3d2s7d.Create_ASP_wordtohtml_aspx() in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\single_storeui\2c329136\f48c1fef\App_Web_wordtohtml.aspx.cdcab7d2.cz3d2s7d.2.cs:0 System.Web.Compilation.BuildResultCompiledType.CreateInstance() +49 System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +115 System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +31 System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +40 System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +139 System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +128 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +161 Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
hezyzPosted May 9, 2009, 6:03 PM
i used your code to convert to html but then i need flash to read it. is html is the best way to use with flash or there is another way u know? thanks hezy ------------ ????? ???
dhana sekarPosted Apr 13, 2009, 8:59 AM
asp.net very useful for me. i need word to html using vb.net
santosh NavlePosted Mar 23, 2009, 2:46 AM
Hi Munir this article is really useful for me but I have fixed format of a Word File which has some Images say Graph and some Points explaining the Grpah. Will you be able to help me out extracting the same format as in word into HTML with the same images and so on.. Pls its Urgent... u can mail me at [email protected]
santosh NavlePosted Mar 23, 2009, 2:45 AM
Hi Munir this article is really useful for me but I have fixed format of a Word File which has some Images say Graph and some Points explaining the Grpah. Will you be able to help me out extracting the same format as in word into HTML with the same images and so on.. Pls its Urgent... u can mail me at [email protected]
Kashyap MakadiaPosted Mar 5, 2009, 7:30 AM
Hi buddy i searched a lot for this i got lots of code for that but smallest and simplest is yours thank you
Rahul NikamPosted Jan 14, 2009, 6:11 AM
hi thanks for code dude... I want to convert HTML page to word document using c# 2.0 for a web site. plz help me. waiting for your replay
AdamPosted Mar 10, 2008, 8:35 AM
Would you please guide me on How to make a file upload control readonly (not editable)? Many thanks
AdamPosted Mar 10, 2008, 8:31 AM
Would you please guide me on How to make a file upload control readonly (not editable)? Many thanks
balakrishnan narendranPosted Feb 18, 2008, 7:00 AM
When i use using Microsoft.Office.Interop.Word i get an error - The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' (are you missing an assembly reference?) Please advise..
Sowjanya KairamPosted Feb 5, 2008, 2:46 AM
I am getting the following error The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' (are you missing an assembly reference?)
Sowjanya KairamPosted Feb 5, 2008, 2:45 AM
I am getting the following error The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' (are you missing an assembly reference?)
Doug BatchelorPosted Dec 18, 2007, 4:09 PM
Munir, I store word docs in sql2005 as image fields. I read the image field into a Byte array and then use MS Word to read the file. Is there any way to avoid using MS Word by taking the byte array and directly converting it to html which can then be displayed in the browser.
murat sapmazPosted Dec 4, 2007, 3:15 PM
hello Munir Shaikh, firstly i thank you, u helped me a lot..but in this article, i did all things u said but i get this error Could not load file or assembly 'Office, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c .. .. ". i uploaded the bin directory which includes the word assamblies but i couldt solve the problem..pleace help me..thanks a lot..
Bibin BabyPosted Nov 22, 2007, 12:04 AM
Can i know how can i convert word contents to MHTML.
loghman dastgheybPosted Jul 31, 2007, 2:18 AM
Hi. Excuse me that I intrupt you. but I think that you would help me. I see that in your article you convert a word file into html. it is very useful. but I want to convert an Excel file to html. I succeeded. but there is a little problem. as you Microsoft.Office.Interop.Word I use Microsoft.Office.Interop.Excel and the way for saveing as an html file is so close to your way. infact they are one. but in Excel we have row and columns. we can select an area and save it. I use the region to select this area by C#. region is provided in that name space(Microsoft.Office.Interop.Excel) but I can't save the area as an html :( I copy them into a new excel file and save it and convert it to html. but the result is not proper. because font and cell width and ... are not acceptable. I see that the Excel itself, when I want save a selected area as an html ask me that you want save the selected area or the whole sheet. you can see it in the SaveDialog that apear when you want to save a selected area in excel and set the output as an HTML file. please Help me if you know how could I save this selection. Thank you for reading my question.
AsifkhanPosted Jul 30, 2007, 6:32 AM
Hi, i m using File upload control of 2.0 framework.I m seleting the file using browse button of file upload control,But due to postback event of any other control on my page the content of file upload control textbox (where the path of selected file is displayed ) gets cleared!!!!!!!!!! I m not getting how to solve this
AsifkhanPosted Jul 30, 2007, 6:31 AM
Hi, i m using File upload control of 2.0 framework.I m seleting the file using browse button of file upload control,But due to postback event of any other control on my page the content of file upload control textbox (where the path of selected file is displayed ) gets cleared!!!!!!!!!! I m not getting how to solve this
nikil kPosted Jul 28, 2007, 3:57 AM
Hi Munir , Great Code Sir. The code works fine but im having problems closing Winword.exe instance from memory. Every time i upload a file a winword.exe instance is created by the currently logged in user and it stays resident in memory. The code objWord.Quit(ref missing, ref missing, ref missing); is not helping in shutting down winword from memory. What do i do to resolve this , as a lot of Winword.exe instances are getting created hence eating up memory. Thank You.
George SellnerPosted Jul 20, 2007, 7:25 AM
Hello, We implemented your solution and it works perfectly on our development machines (XP), but fails to load the document on our Windows server 2003 machine. We granted activate permission to the ASP account using dcomcnf as per your earlier comment. Do you have any insight or suggestions on getting office automation to work in a server setting? Thanks!
Praphulla ChandraPosted Jun 1, 2007, 2:47 AM
Hi Munier,This is Chandra.I used the Same Procedure to convert Word to HTML Convertion.The site worked fine for some time.Suddennly i Got the following Error Error: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80080005 Please Tell me the Solution. Bye
Praphulla ChandraPosted Jun 1, 2007, 2:38 AM
Hi Munier,This is Chandra.I used the Same Procedure to convert Word to HTML Convertion.The site worked fine for some time.Suddennly i Got the following Error Error: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80080005 Please Tell me the Solution. Bye
Habibeh DehbozorgiPosted May 27, 2007, 6:33 AM
Hi Sir, First thank for ur great artile, then how can I convert Excel to Html? when I use a sample code like ur code it give the error below: Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)) by the way it cant open the excel file and give this error Geat Thanks
Vilmar Fernandes da SilvaPosted Apr 20, 2007, 8:39 AM
You dont how you help me with this article. Tks.