In this article I will show you how to export data from a SQL Database (Northwind example) to an Excel spreadsheet, using Office Web Components (OWC). In order to use the OWC COM component, we will have to create a COM wrapper. The data to be exported will be displayed in a DataGrid, and there will be an option to generate the Excel file using the SqlDataReader class.
First of all, I have to say that the strict Microsoft licensing policies regarding OWC prevents you from using OWC on an Internet web server. Personally I think these particular licensing policies are way too strict. Anyway, you can find more info on licensing issues on OWC here.
Now let’s move on with the real deal.

Creating the COM wrapper for OWC
Visual Studio .NET will automatically create the wrapper for you, when adding a reference to the Office Web Components library. Alternatively, when using a basic editor, you might have to create the wrapper yourself using the tlbimp.exe command line utility. We will look at these ways of creating the wrapper.
First, we’ll look at how this is done using VS.NET.




We select Add Reference (right click on the project), select the COM tab, and select the Microsoft Office Web Components DLL. Click OK, and VS.NET will add the reference to your project and create a corresponding wrapper. You will see that the OWC reference has been added to your project.
Using intelli-sense you can now explore the classes, interfaces, delegates and enums of the OWC ‘namespace’.
To manually create the wrapper we use the tlbimp.exe utility. We can find the OWC COM DLL here: \Program Files\Microsoft Office\Office\MSOWC.DLL.
We open up a command prompt and navigate to the directory where MSOWC.DLL resides. Then we issue the following command:


tlbimp msowc.dll /out:dotnetmsowc.dll /namespace:OWC

The /namespace option defines which namespace the wrapper will be known by.
Now we need to move the dotnetmsowc.dll assembly, which contains our .NET wrapper class to the web application’s bin directory.
To find out which classes, interfaces etc. are available (assuming we’re not using VS.NET), we can use the Intermediary Language Disassembler (ildasm.exe). Open ildasm (Start, Run, ildasm) and open the dotnetmsowc.dll assembly. We can now explore all classes, their constructors, methods, attributes etc. as you can see below.




The web form and codebehind file
Our web form will show the data in the DataGrid control. Additionally a textbox for the Excel file name to be exported and a button to perform the export will be displayed at the top of the page.
Have a look at the ASPX file:


<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="cominterop.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
    <title>Exporting Data To Excel, using COM Interop and OWC</title>
  </HEAD>
  <body>
    <form id="Form1" method="post" runat="server">
      Export File Name:
      <asp:TextBox ID="xlfile" Runat="server"></asp:TextBox>
      <asp:Button ID="export2excel" Runat="server" Text="Export to Excel" /><br />
      <br />
      <asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>
    </form>
  </body>
</HTML>

No rocket science there. Note that there is no OnClick or OnServerClick attribute for our ‘Export to Excel’ button. This is because VS.NET adds its own EventHandler for the button’s onclick event, as we can see when we have a look at the codebehind file.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OWC;

namespace cominterop
{
  public class WebForm1 : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.DataGrid DataGrid1;
    private SqlCommand sql;
    protected System.Web.UI.WebControls.Button export2excel;
    protected System.Web.UI.WebControls.TextBox xlfile;
    private SqlConnection cnn;

    private void Page_Load(object sender, System.EventArgs e)
    {
      this.BindDataGrid();      
    }

    private void BindDataGrid() {
      cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;uid=sa;pwd=");
      sql = new SqlCommand("select * from products",cnn);
      cnn.Open();
      SqlDataReader reader = sql.ExecuteReader();      
      this.DataGrid1.DataSource = reader;
      this.DataGrid1.DataBind();
      reader.Close();
      cnn.Close();
    }

    private void WriteDataGrid2Excel() {      
      SpreadsheetClass xlsheet = new SpreadsheetClass();
      cnn.Open();
      SqlDataReader reader = this.sql.ExecuteReader();
      int numbercols = reader.FieldCount;        
      int row=1;      
      while (reader.Read()) {
        for (int i=0;i<numbercols;i++)
        {          
          xlsheet.ActiveSheet.Cells[row,i+1] = reader.GetValue(i).ToString();
        }
        row++;
      }      
      reader.Close();
      cnn.Close();
      xlsheet.ActiveSheet.Export(Server.MapPath(".")+"\\"+this.xlfile.Text,OWC.SheetExportActionEnum.ssExportActionNone);
    }

    private void export2excel_Click(object sender, System.EventArgs e)
    {
      if (this.xlfile.Text.Trim()!="")
      {
        this.WriteDataGrid2Excel();
      }
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      InitializeComponent();
      base.OnInit(e);
    }
    
    private void InitializeComponent()
    {
      this.export2excel.Click += new System.EventHandler(this.export2excel_Click);
      this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion

  }
}

There’s two private methods I’ve added to the WebForm1 class. The BindDataGrid(), which opens the SqlConnection and binds a SqlDataReader object to the DataGrid.
The WriteDataGrid2Excel uses the class properties sql and cnn to open a SqlDataReader object, creates an instance of the SpreadSheetClass class – which we can find in OWC - and loops through all the records. For every record, all column values are being put into a separate cell, using the Cells property on the ActiveSheet object.

NOTE: The error messages you get back from the COM wrapper are not very useful. I had a permissions issue going on when writing the file to disk, and solved it by granting the ASP.NET worker process account write rights to my application folder.

Running the page results in the following screen:




Typing in a filename (ending with .xls) and clicking the ‘Export to Excel’ button will result in an Excel file being written in your web application directory containing the exported data.

Conclusion
In this article we’ve briefly seen how to use existing COM components in the .NET framework (also called COM interoperability). We’ve seen how to generate a COM wrapper, using the tlbimp.exe utility or simply VS.NET.
Also we have made use of Office Web Components to Export data from a SqlDataReader object to an Excel spreadsheet.



Comments
Posted 3 Aug 2002, 6:26 PM
Author lee
Rating 4
i found this article very useful. keep up the good work!
 
Posted 5 Aug 2002, 10:51 AM
Author rubs_eguan
Rating 5
Wow, it's a good article... could anybody referr to any documentation about this in VB???

 
Posted 6 Aug 2002, 9:26 AM
Author Someone
Rating 1
Why would you do this if there will be lots of issues with MS licensing ? What I would do is, instead of using Excel object, I would create a Temperary file, name it with XLS extension, open it and write to it, with a Comma-separator. Why build a wrapper and then use the wrapper. Anyways, you are looping the recordset, just write to the file direct instead of updating the Grid on the Excel sheet.
 
Posted 6 Aug 2002, 10:23 AM
Author Wim
Rating 3
Hi Someone. You could use this for Intranet solutions, where all client machines have an Office 2000 license anyway (or at least should have). Also, reason why you would want native Excel format and not simply comma delimited is that you can use all fancy stuff like formulas and calculations that the Excel Spreadsheet DOM exposes. Furthermore this is also a show case how to create wrappers for COM components and use them in .NET. That was the whole point of the article. Shame you missed it.
 
Posted 7 Aug 2002, 5:39 PM
Author Ivan Vielma
Rating 4
Thank!! for yur article,
bat, I need return Excel Document.

Can you help my???

Bye!!!
 
Posted 7 Aug 2002, 7:34 PM
Author JC Ingram
Rating 5
This is a great effort and a great article the author is very smart and it saved me a bunch of time. THANK YOU WIM!
 
Posted 8 Aug 2002, 6:45 PM
Author John
Rating 4
You can use Excel object to do the same thing. I do not see any advantage in using OWC.
 
Posted 8 Aug 2002, 7:34 PM
Author Wim
Rating 3
John - using OWC is considerably faster than using the standard Office Excel DOM.
 
Posted 14 Aug 2002, 9:57 PM
Author Ivan
Rating 4
Hey, i'm currently working with OWC as well.

I found that this article does give me a great help as a starting point. But I concern one more thing that u didn't mention. which is how to create the interface (eg. ChartSpace, SpeadSheet..etc) in VS.NET platform.

What I have done is just simply drag and drop the ChartSpace component to the interface. But unfortunately, the interface component cannot communicate properly with the codebehind. Do you have any suggested solution??

Thanks!!
 
Posted 16 Aug 2002, 10:41 AM
Author John Straumann
Rating 2
Was a great example until this line:

NOTE: The error messages you get back from the COM wrapper are not very useful. I had a permissions issue going on when writing the file to disk, and solved it by granting the ASP.NET worker process account write rights to my application folder.

I am getting the same error, but how about detailing how to fix it using this "ASP.NET worker process"

J.
 
Posted 16 Aug 2002, 11:23 AM
Author Wim
Rating 3
John - simply right click on your application folder and add the ASPNET account (description: ASP.NET Worker Process) to have Write Permissions. That should solve it.

HTH,
Wim
 
Posted 22 Aug 2002, 8:28 AM
Author Michael B.
Rating 3
Im using the Excel COM by exporting XML with .XSL Stylesheets on the Client site. But now i need to do that on server and saving it to on file. Is there any way to do so, because until now i havn't found any help for that. Where can i find informations about the MS-COM Objects?

If anyone can help me: michael@baarz.de, thanx
 
Posted 28 Aug 2002, 2:53 AM
Author vic
Rating 3
If I want to useing spreadsheet on web how can I do this.

Please help

Thanks!
 
Posted 29 Aug 2002, 7:42 AM
Author niranjan raju
Rating 3
it is an very interesting article, but how to use the namespace in code behind with out having an IDE or an web reference...?

 
Posted 29 Aug 2002, 7:43 AM
Author niranjan raju
Rating 3
it is an very interesting article, but how to use the namespace in code behind with out having an IDE or an web reference...?

 
Posted 29 Aug 2002, 10:06 PM
Author lcxjx
Rating 3
HRESULT ????:0xE004002A
Thanks! Please help!
 
Posted 3 Sep 2002, 12:22 AM
Author Abhay Vaidya
Rating 4
Very Useful article... Helped me a lot giving my clients the interface to save the report as excel...

Good show
 
Posted 4 Sep 2002, 4:05 AM
Author Vasan
Rating 3
Hi..
the article is good and author has done a good job.

can any one tell how should i insert an image into the excelsheet. ie i have to insert my company logo on the first cell..

u can send mail me at vasan@scapevelocity.com

VasanS
 
Posted 5 Sep 2002, 4:44 PM
Author Alejandro Pulgarin Correa
Rating 3
I need to give a cell a formula like "=sum(A1:B5)", and get the result using c#, could you help me with that?
 
Posted 6 Sep 2002, 4:36 PM
Author Jeremy Eubanks
Rating 5
Great article, showing it in VB.NET would have been great!!
 
Posted 7 Sep 2002, 12:21 PM
Author
Rating 4
(Empty)
 
Posted 9 Sep 2002, 10:29 PM
Author cheryL
Rating 3
HI.. Does anyone knows how to do it in VB.NET?
 
Posted 18 Sep 2002, 6:17 PM
Author Kamesh
Rating 3
Hi,
How do i change cell format to string type programatically.
 
Posted 18 Sep 2002, 9:33 PM
Author Nammoc
Rating 3
Hi, How can I load a .xls using OWC
 
Posted 24 Sep 2002, 6:04 AM
Author softjoyer
Rating 3
I do it,but the report is HRESULT Exception:0xE004002A?
LOL,I really mixed,and I must use "reponse" script language to finish my work le


from chinese
 
Posted 13 Oct 2002, 9:23 AM
Author ahmad
Rating 5
kjsshdjshdjshdjshdsssdhdhdddjhdhdjhsdjhds
 
Posted 16 Oct 2002, 7:19 AM
Author yangbo
Rating 3
I do it,but the report is HRESULT Exception:0xE004002A?



from chinese
 
Posted 16 Oct 2002, 3:12 PM
Author Vilen Muruvan
Rating 4
Hi. Is it possible to display the OWC spreadsheet on the web form? i.e. create an instance of the spreadsheet, change a few cell values in code and then view the changed values on the spreadsheet component.

Thanks
 
Posted 23 Oct 2002, 11:19 AM
Author Ru
Rating 3
huinya eto vse
 
Posted 23 Oct 2002, 6:40 PM
Author Ryan Young
Rating 3
VB CODE For the example.

I also thought this was a great article. Due to the amount of requests for code in VB, I am posting the code I that I got when I tried to run this example.
Ryan

'CODE BEGINS HERE
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports OWC

Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
Protected WithEvents xlfile As System.Web.UI.WebControls.TextBox
Protected WithEvents export2excel As System.Web.UI.WebControls.Button
Private WithEvents sql As SqlCommand
Protected WithEvents cnn As SqlConnection




#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
binddatagrid()

End Sub

Private Sub binddatagrid()
cnn = New SqlConnection("Data Source=localhost; Initial Catalog=Northwind; user id=sa;password=hawaii50")
sql = New SqlCommand("Select * from products", cnn)
cnn.Open()
Dim reader As SqlDataReader
reader = sql.ExecuteReader()
DataGrid1.DataSource = reader
DataGrid1.DataBind()
reader.Close()
cnn.Close()

End Sub

Private Sub writedatagrid2excel()
Dim i As Integer
Dim xlsheet As SpreadsheetClass = New SpreadsheetClass()
cnn.Open()
Dim reader As SqlDataReader
reader = sql.ExecuteReader()
Dim numbercols As Integer = reader.FieldCount
Dim row As Integer = 1

While (reader.Read())
For i = 0 To numbercols - 1
Trace.Write("i = " & i)
Trace.Write(row)
Trace.Write(CStr(reader.GetValue(i)))
Trace.Write(numbercols)
xlsheet.ActiveSheet.Cells(row, i + 1) = CStr(reader.GetValue(i)) '.GetType.ToString()
Next
row = row + 1
End While

reader.Close()
cnn.Close()
xlsheet.ActiveSheet.Export(Server.MapPath(".") & "\\" & xlfile.Text, SheetExportActionEnum.ssExport
 
Posted 25 Oct 2002, 2:37 AM
Author Nelson
Rating 3
How about mulitple worksheets in a single workbook?
How can it be done?
 
Posted 8 Nov 2002, 1:35 AM
Author sancho_bang
Rating 3
HRESULT ???? while exporting to excel through datagrid . please help !!
 
Posted 11 Nov 2002, 2:36 AM
Author vinod anand
Rating 4
nice artcile.But i need it to be opened in the browser window.can u put some light on this ??
 
Posted 12 Nov 2002, 4:46 AM
Author sancho_bang
Rating 3
good script. was very helpful. for those getting the HRESULT error try using a csv file instead of xls file
 
Posted 12 Nov 2002, 5:26 AM
Author bha
Rating 3
is Printing Header possible in the excel document. I could only save the records but i want to print the headers along with the records
 
Posted 14 Nov 2002, 8:53 PM
Author snowli
Rating 3
Hi, I got this System.Runtime.InteropServices.COMException: Exception from HRESULT: 0xE004002A. when I tried to export. I notice another 2 people in these comments got the same error too.

To resolve this, give ASPNET write permission to the location where you will create the excel file. (As explained in the note in that tutorial)
 
Posted 16 Nov 2002, 1:54 AM
Author Dream (Male)
Rating 5
GOOD.
 
Posted 20 Nov 2002, 4:36 AM
Author Rain
Rating 3
Title: HRESULT problem!!!

Error occur as following:
Exporting Data to Excel using COM Interoperability and Office Web Components (OWC) in ASP.NET

HRESULT ???? while exporting to excel through datagrid . please help !!


 
Posted 23 Nov 2002, 8:41 AM
Author Chris RC
Rating 5
Excellent helpful article
 
Posted 26 Nov 2002, 4:44 AM
Author pennie
Rating 5
nice
 
Posted 26 Nov 2002, 9:00 AM
Author Claudio_Italy
Rating 5
Hi,
Very,Very Good Sample.
It's run under VB.NET, very good
Thank's from Claudio (Italy
 
Posted 26 Nov 2002, 4:04 PM
Author winter
Rating 3
What is the advantage of this code over the following -
<%Response.ContentType = "application/vnd.ms-excel"%>
 
Posted 26 Nov 2002, 8:47 PM
Author pennie
Rating 5
To "HRESULT error".
Don't be careless so much.
Please type in the filename not path in the textbox.
Default path is gotten from Server.MapPath.If you don't change program,please copy a excel to that directory.

A chinese girl
 
Posted 2 Dec 2002, 12:55 AM
Author wan mohd afendi
Rating 3
I get this eror on
SpreadsheetClass excel = new SpreadsheetClass();

The error message is:


The specified module could not be found
System.IO.FileNotFoundException
 
Posted 2 Dec 2002, 2:30 AM
Author Krishna
Rating 3
Hi,

I am getting this error when I ran this code

Server Error in '/TestAsp' Application.
--------------------------------------------------------------------------------

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'cominterop.WebForm1'.

Source Error:


Line 1: <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="cominterop.WebForm1" %>
Line 2: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
Line 3: <HTML>


Source File: C:\Documents and Settings\krishnasp\Desktop\TestAsp\WebForm1.aspx Line: 1


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.0.3705.0; ASP.NET Version:1.0.3705.0

could some one tell me how do I fix this.

Regards,
Krishna S P
 
Posted 10 Dec 2002, 2:05 AM
Author bruce
Rating 3
Is there anybody can tell me how to create excel file at client side.(From China Shang Hai)
 
Posted 13 Dec 2002, 2:42 PM
Author Michael Marcavage
Rating 5
This worked but the rows are wierd
the dates are cut off
how do I make this a clean export and have all of the information correctly in the Excel File
 
Posted 31 Dec 2002, 1:59 AM
Author porKiller
Rating 5
reply to S.H. bruce:
just by "Response.Redirect(path);"
of course "path=TextBox_exportFileName.Text"(Assume a webcontrol--TextBox_exportFileName is used to specify the export fileName.)
------im porKiller from WuHan ^_^.
but i cannot customize the font,the color and the columns' width of the export File.
 
Posted 6 Jan 2003, 4:16 AM
Author may
Rating 3
Does anyone know how to open Words document instead for processing?
 
Posted 12 Jan 2003, 1:47 AM
Author David Austin
Rating 3
It works! In VB it works like this:
Private Sub ExportXL()
Dim xlsExport As OWC.SpreadsheetClass = New OWC.SpreadsheetClass()
Dim numbercols As Integer
Dim myRow As DataRow
Dim myCol As DataColumn
Dim intRowCounter As Integer = 1
Dim intColCounter As Integer

ProcessData(True) 'fill the dataset using my method

Dim myDataTable As DataTable = Me.dsUccFilings1.Tables(0) 'Assign the table to the table obj

Dim currRows() As DataRow = myDataTable.Select(Nothing, Nothing, DataViewRowState.CurrentRows)

If (currRows.Length < 1) Then
'No Current Rows Found
Else
'rows found
'write the column names to the spreadsheet
intColCounter = 1
For Each myCol In myDataTable.Columns
xlsExport.ActiveSheet.Cells(intRowCounter, intColCounter) = myCol.ColumnName.ToString
intColCounter = intColCounter + 1
Next
intRowCounter = intRowCounter + 1 'go to second row for writing data

'iterate through the columns in each row and write the contents to a table cell
For Each myRow In myDataTable.Rows
intColCounter = 1
For Each myCol In myDataTable.Columns
xlsExport.ActiveSheet.Cells(intRowCounter, intColCounter) = myRow(myCol).ToString()
intColCounter = intColCounter + 1
Next
intRowCounter = intRowCounter + 1
Next
End If

'fix the filename extension if invalid
With Me.txtXLSExportFilename
If Not .Text.EndsWith(".xls") Then
.Text.Concat(".xls")
End If
End With

'Export the spreadsheet
xlsExport.ActiveSheet.Export( _
context.Request.ApplicationPath & System.IO.Path.AltDirectorySeparatorChar & _
"TempFiles" & System.IO.Path.AltDirectorySeparatorChar & _
Me.txtXLSExportFilename.Text.ToString, _
OWC.SheetExportActionEnum.ssExportActionNone)

End Sub
 
Posted 13 Jan 2003, 9:44 PM
Author Manish
Rating 2
A good start on Excel.Wanted to know how graph could be exported!!
 
Posted 16 Jan 2003, 6:12 AM
Author Paolo Corti
Rating 4
"HRESULT error"
this is because you need to set WRITE permission to the ASP.NET user for the web directory where you are exporting the xls file.
have fun
 
Posted 17 Jan 2003, 4:06 AM
Author kumar
Rating 2
hi i get this error


Parser Error Message: Could not load type 'cominterop.WebForm1'.

Source Error:


Line 1: <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="cominterop.WebForm1" %>
Line 2:
Line 3: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >


im not able ot get thru
Please hlp me
kumar
 
Posted 22 Jan 2003, 2:15 AM
Author heping
Rating 5
I have a Error,Please help me.
CODE:
private void WriteDataGrid2Excel()
{
SpreadsheetClass xlsheet = new SpreadsheetClass();
string connString = (string)ConfigurationSettings.AppSettings["DSN"];
string sql = "select id,yhm,mm,yhjb,ckjb,ckm,kfckcb,bz from gcch_xtyh";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int numbercols = reader.FieldCount;
int row=1;
while (reader.Read())
{
for (int i=0;i<numbercols;i++)
{
xlsheet.ActiveSheet.Cells[row,i+1] = reader.GetValue(i).ToString();
}
row++;
}
reader.Close();
conn.Close();
xlsheet.ActiveSheet.Export(Server.MapPath(".")+"\\"+TextBox_file.Text,OWC.SheetExportActionEnum.ssExportActionNone);
}

ERROR:
??: ???? Web ????,??????????????????,??????????????????????????

??????: System.Runtime.InteropServices.COMException: HRESULT ????:0xE004002A?

???:
xlsheet.ActiveSheet.Export(Server.MapPath(".")+"\\"+TextBox_file.Text,OWC.SheetExportActionEnum.ssExportActionNone);
 
Posted 10 Feb 2003, 10:39 AM
Author Duncan
Rating 3
Wim,
A good article, but as I (really) want to be 'license clean', I guess I can't use this.....
I went into my wxcel (xp version) and saved as an xml file. Looked at the result and it all looked (fairly) straight forward.(Though I'm sure I'm underestimating the complexity!)

What I'm a bit surprised at is that there isn't a library that takes a dataset and allows you to save that as an excel(xml) compatible sheet.
or is there?
regards,
Duncan.
 
Posted 14 Feb 2003, 8:35 AM
Author abdel
Rating 1
namespace OWC not found!
plaese help me! thank you!
 
Posted 14 Feb 2003, 8:37 AM
Author abdel
Rating 1
namespace OWC not found!
please hlp me! thank you! tabti@web.de
 
Posted 7 Mar 2003, 7:13 AM
Author Groundhog
Rating 4
Same Error HRESULT ????:0xE004002A..
Any solutions - can't see an answer anywhere....
 
Posted 7 Mar 2003, 10:55 AM
Author Naveen
Rating 5
This article is very useful. Thanks
 
Posted 12 Mar 2003, 5:09 AM
Author Silvano
Rating 3
Sorry, but the output is XML not Excel native format ... or not.
 
Posted 14 Mar 2003, 7:41 PM
Author Joe
Rating 5
It is very cool, can you show me how to display
a line chart using Office Web Component in ASP.NET ?

Thanks a million
Joe
 
Posted 25 Mar 2003, 4:17 AM
Author asit
Rating 4
good graphic illustrations and organization of content
 
Posted 2 Apr 2003, 11:37 PM
Author Vaishali
Rating 3
hi,
I converted this C# code in vb.net
But it writes only 1st column and 1st row in Excel file. Plz give the solution. Following is my vb.net code

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Imports OWC

Public Class WebForm6
Inherits System.Web.UI.Page
Protected WithEvents xlfile As System.Web.UI.WebControls.TextBox
Private sql As SqlCommand
Private cnn As SqlConnection
Protected WithEvents export2excel As System.Web.UI.WebControls.Button
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
Protected Overrides Sub OnInit(ByVal e As EventArgs)
'
' CODEGEN: This call is required by the ASP.NET Web Form Designer.
'
InitializeComponent()
MyBase.OnInit(e)
End Sub
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()


End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Me.BindDataGrid()
End Sub

Private Sub BindDataGrid()
cnn = New SqlConnection("Initial Catalog=office_auto_1;Data Source=AMAZON;user id=sa;password=liohpt01")
sql = New SqlCommand("select * from Project", cnn)
cnn.Open()
Dim reader As SqlDataReader = sql.ExecuteReader()
Me.DataGrid1.DataSource = reader
Me.DataGrid1.DataBind()
reader.Close()
cnn.Close()
End Sub

Private Sub WriteDataGrid2Excel()
Dim xlsheet As SpreadsheetClass = New SpreadsheetClass()
cnn.Open()
Dim reader As SqlDataReader = Me.sql.ExecuteReader()
Dim numbercols As Integer = reader.FieldCount
Dim row As Integer = 1
While reader.Read()
Dim i As Integer
For i = 0 To numbercols - 1 Step i + 1
xlsheet.ActiveSheet.Cells(row, i + 1) = reader.GetValue(i).ToString()
Next
row = row + 1
End While
reader.Close()
cnn.Close()

xlsheet.
 
Posted 3 Apr 2003, 3:12 AM
Author noname
Rating 4
hi,
can anyone tell me, how to export a file on client's machine?
 
Posted 3 Apr 2003, 3:12 AM
Author noname
Rating 4
hi,
can anyone tell me, how to export a file on client's machine?
 
Posted 7 Apr 2003, 12:31 PM
Author Lily Feng
Rating 5
How to put header text on this excel file displayed in IE? Please help!
 
Posted 16 Apr 2003, 10:56 AM
Author yog
Rating 3
Good Article specially for those who has no idea of exporting excel data, my program is running except its not creating any xls file
 
Posted 3 Jun 2003, 5:45 PM
Author tkm
Rating 3

"xlsheet.ActiveSheet.Export..." generates the following error :-

System.Runtime.InteropServices.COMException: Exception from HRESULT: 0xE004002A.

Any idea on how I can fix this?

Thanks!

 
Posted 10 Jun 2003, 4:00 AM
Author Neo
Rating 1
Its not working at all.... there is no excel file been generated..
 
Posted 13 Jun 2003, 4:32 PM
Author jwidel
Rating 3
I'm a newby to vb.net... and This will be really helpful to me. How do I tie this to the export2excel button click event?
 
Posted 13 Jun 2003, 5:19 PM
Author Jwidel
Rating 3
My qyery uses an OleDB database and runs fine but when I click the export2excel button I get the following:

Exception Details: System.Data.OleDb.OleDbException: No error information available: DB_E_PARAMNOTOPTIONAL(0x80040E10).

My code looks like this:
Private Sub writedatagrid2excel()
Dim i As Integer
Dim xlsheet As SpreadsheetClass = New SpreadsheetClass
Dim Reader As System.Data.OleDb.OleDbDataReader

OleDbConnection1.Open()

Reader = OleDbCommand1.ExecuteReader()
Dim numbercols As Integer = Reader.FieldCount
Dim row As Integer = 1
While Reader.Read()
For i = 0 To numbercols - 1 Step i + 1
xlsheet.ActiveSheet.Cells(row, i + 1) = Reader.GetValue(i).ToString()
Next
row = row + 1
End While

Reader.Close()
OleDbConnection1.Close()

xlsheet.ActiveSheet.Export(Server.MapPath(".") & "\\" & xlfile.Text, SheetExportActionEnum.ssExportActionNone)

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (xlfile.Text.Trim() <> "") Then
writedatagrid2excel()
End If
End Sub
 
Posted 30 Jun 2003, 6:42 PM
Author Joe
Rating 5
To solve the Error HRESULT ????:0xE004002A..

you have to right clik your folder application and in the security pad you select the aspnet user and give it write permissions
 
Posted 9 Jul 2003, 12:15 PM
Author Homero Lara
Rating 3
Good article simple and straight to the point....thanks
 
Posted 18 Aug 2003, 7:55 PM
Author sk
Rating 5
Static variables?

For some reason I have to specify that instead of private SqlCommand sql;
private SqlConnection cnn;

I had to change it to

static public SqlCommand sql;
static public SqlConnection cnn;

Otherwise works great.
 
Posted 20 Aug 2003, 4:26 PM
Author rjwelte
Rating 3
Helo Wim:
I'm using this article to produce a spreadsheet. What I want to do now is format the sheet programatically. Do you have any suggestion on how to specify a range object for a row, column and a cell?

john welte
 
Posted 17 Sep 2003, 12:14 PM
Author ahmed
Rating 3
But the data is exported to excel in xml format. Please let me know how to export actual data to excel
 
Posted 21 Sep 2003, 3:46 PM
Author Sis
Rating 4
Great article, glad I found it.

However, I am getting an error where I store values in the cell:

oExcel.ActiveSheet.Cells(1, 1)=""

The error is "QueryInterface for interface OWC.IWebCalc failed"

Dont see anyone else having the same problem, what am I missing?

I am not using VS so I used the tlbimp command to create the dll, moved the dll to the bin folder of the application. So can someone tell me what I did wrong?

Thank you.
 
Posted 23 Sep 2003, 4:24 AM
Author Prasanna
Rating 3
Can Anybody Let me Know ??

HOW TO OPEN EXCEL TEMEPLETE TO WRITE IN WITH THE HELP OF OWC ??
Its so easy ?????

Thanks in advance...
bye bye...

(Article is start of something GREAT !!)
 
Posted 28 Oct 2003, 10:46 AM
Author sri
Rating 3
I find this article great when i started the similer functionality in my project. But i am getting error when i am trying to set the bod property for the fonts in the rage.

Do i need any ground work like setting permissions or something else to work this in my page.

I am seeking help in formating the excel cells like colouring, font change , bold etc..

Thanks in advance ... cheers to wim for providing this useful article


 
Posted 28 Oct 2003, 8:22 PM
Author Anand
Rating 3
Good one!!!!!!!!!!!!!!!!
 
Posted 17 Nov 2003, 4:17 PM
Author Dana
Rating 4
Who the hell would want to use VBScript when C# is so much better...

I am having a problem... The following code does not work:

SpreadsheetClass xlsheet = new SpreadsheetClass();
xlsheet.ActiveSheet.Cells[0,0] = 0;


I get the following error:

System.ArgumentException: The parameter is incorrect

Anybody know what's going on?

Thanks,

-D
 
Posted 20 Dec 2003, 4:52 AM
Author chandu
Rating 3
Using OWC component I am able to generate Excel file. Now, the problem is, I am not able to set any property to cells, like width, font etc. Can any body help me in solving the problem.
 
Posted 13 Jan 2004, 9:44 AM
Author Steven
Rating 4
Excellent example, I had this working in under 5 minutes.

btw Dana;

The ActiveSheet.Cells start at [1,1], that's why you are getting that error.
 
Posted 22 Jan 2004, 6:01 PM
Author Silvia Brunet Jones
Rating 5
Help I get this error

COM object with CLSID {0002E510-0000-0000-C000-000000000046} is either not valid or not registered.
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.Runtime.InteropServices.COMException: COM object with CLSID {0002E510-0000-0000-C000-000000000046} is either not valid or not registered.

Source Error:
 
Posted 26 Feb 2004, 5:13 AM
Author brahma
Rating 4
it is excellent article
 
Posted 2 Mar 2004, 7:49 AM
Author Praveen
Rating 4
how can we set property of perticular cell like font color or size
 
Posted 2 Mar 2004, 7:49 AM
Author Praveen
Rating 4
how can we set property of perticular cell like font color or size
 
Posted 2 Mar 2004, 7:50 AM
Author Praveen
Rating 4
how can we set property of perticular cell like font color or size
 
Posted 3 Mar 2004, 2:49 AM
Author Sreedhar
Rating 4
This article is very good
 
Posted 4 Mar 2004, 5:17 AM
Author vinod
Rating 5
HERE IS A SAMPLE TO CODE TO AUTOMATE EXCEL FROM VB.NET. NEED TO INSTALL THE OFFICEXP INTEROP ASSEMBLIES BEFORE IT WILL WORK AND SET REFERENCE TO THE EXCEL OBJECT LIBRARY. MAIL ME IF U NEED ANY FURTHER INFO.

I RIPPED THIS CODE FROM SOMEONE ELSE's SITE AND WAS TOO LAME TO MENTION IT. HENCE THE FOLLOWING NOTE FROM WIMDOWS.NET:

The copied and pasted code by Vinod can be found in its entirety at Kelly's site: http://www.kjmsolutions.com/datasetarray.htm

This is a community site, please let's keep it that way and give credit where credit is due. No problem copying and pasting code, but have the courtesy to mention your source.

Thanks for everyone's cooperation
.

Regards,
Wim Hollebrandse
 
Posted 6 Mar 2004, 3:55 AM
Author Hardik Mehta
Rating 3
Hello Vinod,

sir i don't have file for excel9.ole.
i have used file of office 2000 but i didn't got enough properties for that.
so please send me file for office xp (Excel9.OLE).


waiting for your reply,
Hardik Mehta.
 
Posted 11 Mar 2004, 3:16 AM
Author Syed Aun Ali
Rating 3
Hello,
I go through the article really it is nice, i am using Excel Application in my Asp.Net page. for this i used Excell Application, workbook, workshee class. I am using vb as script for coding. Simple of my code is
Dim xlApp as Excel.Application
Dim xlwBook as Excel.Workbooks
Dim xlwSheet as Excel.Workshee
xlApp=new Excel.Application
'for checking the status of excel i make it visible
xlapp.visible=true
xlwBook=xlApp.Workbooks.open("filename")
xlwSheet=xlwBook.Sheets(1)
' some operation on Excel Sheet
'
xlwBook.save()
xlwBook.Close()
xlApp.Quit

This is the style i am using for intraction with an Excel Sheet, i am closing workbook and Quiting Application, But it is not removing from Task Manager and not woriking if i like to use the same Workbook again.
So, Pls help me to solve the problem, I am using VB as Script
Waiting for your Suggession

Mail us: s_aunali@yahoo.com





 
Posted 3 Apr 2004, 11:57 AM
Author Kavitha
Rating 1
vinod,

I am Using the Excel.Application Object and Excel.Visible=true ,But the Excel Open in Server not in Client WebBrowser How can i solve this problem.

Please Reply

Regards
Kavithaa C
 
Posted 16 Apr 2004, 7:01 AM
Author Silvia
Rating 5
Is it possible create a temporary file without save in the filesystem?
 
Posted 26 Apr 2004, 3:16 AM
Author lan
Rating 3
this example in only for server's machine

can anyone tell me, how to export a file on client's machine?

 
Posted 6 May 2004, 4:36 PM
Author bloodrayne4
Rating 3
here is the the export used to export to a clients machine it will render in their browser

Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)

'simply put the control you want rendered in place of the word datagrid below i have used it with literals and datagrids i bind the grid and after that put this code and it all comes out in excel

datagrid.RenderControl(hw)

Response.Write(tw.ToString())
Response.End()
 
Posted 6 May 2004, 4:41 PM
Author bloodrayne4
Rating 3
e.g.

<script runat = "server">
sub page_load()
sqlstr = new sqlcommand("select * from tablename",connections)
connections.open()
d.datasource = sqlstr.executereader()
d.databind
connections.close()
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
d.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
end sub
</script>
<html><body><form runat = "server">
<aspatagrid id = "d" runat = "server" autogeneratecolumns = "true" cellspacing = "0" cellpadding = "4" BorderWidth="1" bordercolor = "red"/>
</form></body></html>
 
Posted 18 May 2004, 7:05 AM
Author scorpion53061
Rating 3
This message is for vinod:

IT IS CUSTOMARY TO SITE YOUR SOURCE FOR YOUR SOURCE CODE IF YOU DID NOT WRITE IT........ESPECIALLY IF YOU ARE COPYING AND PASTING.



AND YES.......I DID.

http://www.kjmsolutions.com/datasetarray.htm



 
Posted 19 May 2004, 12:21 AM
Author William Ryan
Rating 3
Vinod, what is the matter with you. The code you posted is so obviously stolen you should be ashamed of yourself. Couldn't you at least change the variable names? And the cute little thing with changing the cell reference from A2 to A20.... are you kidding? You need to leave 19 rows for the 'header row'? It's bad enough you steal the dude's code, but steal his comments too? At least cite the place you got it, otherwise you are being a scumbag. That would get you kicked out of any class and probably college and if you got caught plagarizing that flagrantly you'd probably get your degree stripped if it was discovered. And for God's sake, if you are going to steal someone else's work, at least change the comments or change the logic so that your comments make sense. This is shameful. As a programmer you will make your money selling your intellectual property and you wouldn't like people stealing your work - SO DON'T DO IT TO OTHER PEOPLE!
 
Posted 19 May 2004, 7:04 AM
Author scorpion53061
Rating 3
Thanks Bill.

I sure wish Vinod would come out of hiding.
 
Posted 19 May 2004, 10:33 AM
Author CodeMeNow
Rating 3
I didn't see a copyright or disclaimer on that page on kjmsolutions. It is his own fault if he gets his ideas ripped off. I would like to know where kjm ripped it off from?
 
Posted 19 May 2004, 11:59 AM
Author skicow
Rating 3
CodeMeNow,

It's not a question of copyright or getting ripped off, it's a question of ethics pure and simple. It's common curtesy to link to where you got the code from, and say that you were not the original writer of the code.

As for where kjm got the code, I'm sure he wrote it himself.
 
Posted 19 May 2004, 2:08 PM
Author CodeMeNow
Rating 3
Perhaps if you did not live in a fantasy world where all was just and right that would be true. But it is not so.

What makes you so sure he did not steal it himself?
 
Posted 20 May 2004, 8:38 AM
Author skicow
Rating 3
Wow, that's a good argument! This world sucks so why should we try to be nice any more? Lets all just be a-holes and screw everyone else.

Please, give me a break. You are 100% correct that this world is not 'just and right', but it being so does not make it an excuse to do wrong IMHO.

What makes you so sure he stole it? As for what makes me so sure that kjm (scorpion53061) didn't steal the code is because I believe in the phrase 'innocent until proven guilty' maybe you've heard of it? Vinod was proven guilty.
 
Posted 20 May 2004, 9:02 AM
Author CodeMeNow
Rating 3
My suggestion to you and to kjm is to get over it and welcome to the real world. I would have done the same thing as Vinod had he posted the code without any sort of copyright notice.

The fact is if you put it on the web EXPECT it to be stolen.

If you can't handle that get out of the business.
 
Posted 20 May 2004, 3:11 PM
Author skicow
Rating 3
I think you are missing my point...I NEVER said that he stole it, I just stated that it would have been nice if he would have stated the source of the code. You said that kjm 'ripped it off' the code, I did not.

As for your welcome to the real world, I thank you, because before now I was living in a world where there were gum drop houses and lollipop lanes....I know that if you post code on the web it will get copied and used, that's why it 's posted there! So other people can get help with a problem they are having, it's free to be used by anyone, and it's posted by people who are being nice and trying to help other people. You are right, Vinod didn't have to say where he got it from, but it would have been NICE if he stated where he got the code from. It seems like you have a problem with being nice.

BTW what 'business' are you refering too? The business of posting code on the Internet?
 
Posted 24 May 2004, 5:55 PM
Author scorpion53061
Rating 3
I assure you CodeMeNow, I wrote this piece.

Now as far as the law is concerned from what I understand even if a person does not "copyright" the code does not give implicit permission for another to steal it. Case law is full of instances where people got sued for stealing "intellectual property" where no notice of copyright was posted.

Not that I would ever sue. If he had lifted the comments out and shown some effort at improving the code I would have really been okay with that. And this whole thing would have never happened.
 
Posted 2 Jun 2004, 9:18 AM
Author muthukarthikeyan
Rating 3
hai,

if i am using ths same concept in vb.net
what can i do
 
Posted 8 Jun 2004, 9:19 PM
Author scorpion53061
Rating 3
the code is in vb.net

I do not understand your question....
 
Posted 15 Jun 2004, 5:06 PM
Author sachin
Rating 4
Hi,
Does anyone has idea of disadvantages of excel automation on server side? what versions it will support and how to mitigate this risk?

thanks,
sachin
 
Posted 15 Jun 2004, 6:32 PM
Author Jagan
Rating 3
Hi,
How to read a xls/csv file in Asp.net.
Please help me.
Thanks a lot, Jagan
 
Posted 18 Jun 2004, 2:34 PM
Author Priya
Rating 3
I need to validate a Formula calculated cell in the OWC Spreadsheet component. Which event will trigger for the calculated value cell. I tried the SheetCalculate event but not working. Any help would be appreciated.
Thanks a lot,
Priya
 
Posted 22 Jun 2004, 6:15 PM
Author Sachin Patil
Rating 3
hi,
Some one was looking for the disadvantages of excel automation on server side look at the following link, its knowledge base article 257757
http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q257/7/57.asp&NoWebContent=1

There are alternative solutions also available on this web page
regards,

Sachin Patil
 
Posted 24 Jun 2004, 10:46 AM
Author Anaconda
Rating 4
Hola

Alguien puede ayudarmeen este problema.

Me gustaria que a través de OWC pueda manipular template de excel(.tld), ya que con esto no tendria que estar formatendo la pagina ni estar insertando un logo.

 
Posted 20 Jul 2004, 3:11 PM
Author kiran
Rating 3
good!! I came to know many things with this article.Nice article...Good work by the author of this article.
 
Posted 7 Sep 2004, 10:13 AM
Author ash
Rating 3
Hi
it's good article.
i m geeting one problem that whenever i put file name in text box and click the button ,i m not geeting excel file .
can anyone help please
it's very urgent
 
Posted 7 Oct 2004, 8:02 PM
Author eric
Rating 5
I am agree with that guy.c# is difficule for me.I always used VB.If someone have one written by VB,please sent one piece to me .thank you.
 
Posted 14 Oct 2004, 7:04 AM
Author
Rating 3
Help me !
I want add rows to Sheet in Excel using C#
 
Posted 29 Oct 2004, 6:23 PM
Author Adolfo López
Rating 2
Your script is able to write an .xls file, if I want to show same file I inserted this line: Response.Redirect(todo);where todo contains file's path, but when this line is executed, it display excel file into a webform, I need to display excel file as an excel application containing all buttons availables in an excel application, does nybody know how to achieve it?
 
Posted 24 Nov 2004, 6:55 AM
Author krishnaveni
Rating 3
i want to read values from excel sheet to datagrid how it can be possible
 
Posted 25 Nov 2004, 11:38 AM
Author bottoj
Rating 4
When I export a spreadsheet using this example I get an XML file. Can anybody let me know how to get a normal excel fromat file?
 
Posted 14 Dec 2004, 3:15 AM
Author cookie
Rating 5
it's a perfect article.

but when i granted the write permission to the application folder. The problem still exsist.
Even I granted all right to anyone,I still got the 0xE004002A error . What can i do?
 
Posted 21 Dec 2004, 3:59 PM
Author Eric Christianson
Rating 5
Outstanding article! All the code works as is, perfectly. How rare is that?!

For those folks who are getting the [HRESULT ????:0xE004002A.. ] error, try deleting the first spreadsheet you created before reeplacing it with one with the same name.
For those who need a header, try adding the following outside the loop:

CreateHeader(xlsheet);
.
.
.
private void CreateHeader(OWC.SpreadsheetClass xlsheet)
{
  xlsheet.ActiveSheet.Cells[1,1] = "Column1";
xlsheet.ActiveSheet.Cells[1,2] = "Column2";
  xlsheet.ActiveSheet.Cells[1,3] = "Column3";
}

Moral of the story... Try a little experimentation before asking - that's the fun of C#!
 
Posted 23 Dec 2004, 7:23 AM
Author reckless
Rating 4
code is excellent, working fine..
i want to add 1 more sheet to the same workbook from different table while exporting. is it possible to do that.. if any one knows help me.

thanks in advance

reckless
 
Posted 29 Dec 2004, 4:11 PM
Author mek
Rating 3
Hi,

Please help mw ith this. Its URGENT!!!

What is the way for writing data FROM EXCEL sheet TO SQL DATABASE???
 
Posted 30 Dec 2004, 5:20 AM
Author panky
Rating 3
Hi
this is nice artical,keep it up,but the i want insted of opening excel sheet it should be display on the webpage like data in the Datagrid,can
we use excel same as datagrid,so that we can manuplate data in excel
sheet.Pls if any one knows help
thanks
panky
 
Posted 24 Jan 2005, 8:22 AM
Author samit
Rating 4
How we can do formatting to Excel via asp.net using OWC11. Formatting means changing colour , font , alignment of particular cell. Thanks
 
Posted 31 Jan 2005, 12:20 PM
Author ishy
Rating 3
Query Interface for Interface OWC.IwebCalc failed.

Does anyone know how to get rid of this error?

Thanks in advance.
 
Posted 31 Jan 2005, 12:25 PM
Author ishy
Rating 3
BTW to format the excel cells from the VB code you can try this with your own variations

With xlSheet.Range("A1")
.Font.Bold = True
.Font.Color = "Blue"
.EntireColumn.AutoFitColumns()
End With

With xlSheet.Range("B1")
.Font.Bold = True
.Font.Color = "Blue"
.EntireColumn.AutoFitColumns()
'date format
.EntireColumn.NumberFormat = "dd-MMM-yyyy"
End With

With xlSheet.Range("C1")
.Font.Bold = True
.Font.Color = "Blue"
'time format
.EntireColumn.NumberFormat = "hh:mm:ss AM/PM"
.EntireColumn.AutoFitColumns()
End With

With xlSheet.Range("E1")
.Font.Bold = True
.Font.Color = "Blue"
.EntireColumn.AutoFitColumns()
'time format
.EntireColumn.NumberFormat = "h:mm:ss"
End With

With xlSheet.Range("D1")
.Font.Bold = True
.Font.Color = "Blue"
.EntireColumn.AutoFitColumns()
End With