Microsoft.Office.Interop.Excel.Application

A

Andie

Hi All,


I am using Microsoft.Office.Interop.Excel.Application COM to create a Excel
spreadsheet, and write the value (not from any dataset) into that
spreadsheet, and then StreamWrite to the disk.

For some reason, the following code is not working.

This is the declaration of ws:
Microsoft.Office.Interop.Excel.Worksheet ws
=(Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];

ws.Cells[1, 1] = "CardNo";
ws.Cells[1, 2] = "PharmacyName";
ws.Cells[1, 3] = "CostPerCard";

sw.Writer(ws.Cells[1, 1]);
sw.Writer(ws.Cells[1, 2]);
sw.Writer(ws.Cells[1, 3]);

I thought this code will write to the spreadsheet like this:
A | B | C
-----------------------------------------------
CardNo | PharmacyName | CostPerCard

but, it wrote to spreasheet like this, all them just in column A:
A
-----------------------------------------------
System.__ComObjectSystem.__ComObjectSystem.__ComObjectH40655


I have been spent quite lots of time on it, but still couldn't work it out.

Thanks heaps
 
M

Manvir Singh

ws.Cells[rowIndex, colIndex] has a return of type *object* (which is a
boxed object for Excel.Range).

So, sw.Write(ws.Cells[1, 1]) will call the ToString() method for the return
value of ws.Cells[1, 1] (which is object), and only its type information
will get written to the stream three times(i.e., System.__ComObject).

In order to write the correct value to the stream, please try typecasting
the ws.Cells[] to Excel.Range, as following:

sw.Write( ((Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 1]).Text );
sw.Write( ((Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 2]).Text );
sw.Write( ((Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 3]).Text );

Regards,
Manvir Singh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top