Reputation: 460
I need help with this script. I'm using Word Interop but I get the following error, why?
thanks.
The Error
Object reference not set to an instance of an object. 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.NullReferenceException: Object reference not set to an instance of an object.
catch (Exception ex)
{
oDoc.Close(ref o, ref o, ref o);
ClientScript.RegisterStartupScript(this.GetType(), "error Kobie Williams", "javascript:;alert('" + ex.Message + "')");
}
In Line
oDoc.Close(ref o, ref o, ref o);
.CS
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//creating instance of word application
Microsoft.Office.Interop.Word._Application w = new Microsoft.Office.Interop.Word.Application();
object path = @"C:\inetpub\wwwroot\WebSite1\Kobie_Williams\id.docx";
object read = "ReadWrite";
object readOnly = false;
object o = System.Reflection.Missing.Value;
//opening document
Microsoft.Office.Interop.Word._Document oDoc = w.Documents.Open(ref path, ref o, ref readOnly, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
try
{
//loop for each paragraph in document
foreach (Microsoft.Office.Interop.Word.Paragraph p in oDoc.Paragraphs)
{
Microsoft.Office.Interop.Word.Range rng = p.Range;
Microsoft.Office.Interop.Word.Style styl = rng.get_Style() as Microsoft.Office.Interop.Word.Style;
//checking if document containg table
if ((bool)rng.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdWithInTable)
== true)
{
//loop for each cell in table
foreach (Microsoft.Office.Interop.Word.Cell c in rng.Cells)
{
if (rng.Cells.Count > 0)
{
//checking for desired field in table
if (c.Range.Text.ToString().Contains("ID"))
//editing values in tables.
c.Next.Range.Text = "1";
if (c.Range.Text.ToString().Contains("Name"))
c.Next.Range.Text = "Haider";
if (c.Range.Text.ToString().Contains("Address"))
c.Next.Range.Text = "Kobie-Williams";
}
}
//saving document
oDoc.Save();
}
}
//closing document
oDoc.Close(ref o, ref o, ref o);
}
catch (Exception ex)
{
oDoc.Close(ref o, ref o, ref o);
ClientScript.RegisterStartupScript(this.GetType(), "error Kobie Williams", "javascript:;alert('" + ex.Message + "')");
}
}
Upvotes: 0
Views: 3333
Reputation: 7211
It's likely oDoc is null because the file failed to load on w.Documents.Open()
. You need to do something like
if (oDoc != null)
oDoc.Close()
Also, this should be done only once in the finally
block, not repeated in both the try
and catch
blocks.
Also, using Office Interop is generally a bad idea on web servers: Is Microsoft.Office.Interop safe to use for (file-converting) for a website?
Upvotes: 1