.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Excel problem

Posted By:      Posted Date: September 24, 2010    Points: 0   Category :ASP.Net

Hi all,

             I am trying to fetching the data from Book1.xlsx file. The program is not working and throws an exception.Please check the code and tell me where I am doing the mistake?


protected void Page_Load(object sender, EventArgs e)
        string con = ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString;

        using (OleDbConnection myConnection = new OleDbConnection(con))
                OleDbCommand myCommand = new OleDbCommand("SELECT * FROM [Cities$]", myConnection);
                 OleDbDataReader reader = myCommand.ExecuteReader();

                    GridView1.DataSource = reader;
            catch (Exception ex)
                Response.Write("An error: " + ex.Message);

The exception is:

An error: The Microsoft Office Access database engine cannot open or write to the file ''. It is alre

View Complete Post

More Related Resource Links

While Importing Excel 2007 file to Datatable - headerrow problem


Hi there,


I am trying to simply extract an excel data from an uploaded file an put it into a datatable. In this case the excel file has 3 rows but when I fill the datatable I only see row count of 2.

I tried changing HDR:NO; to HDR:YES and vice versa, but no luck. 

What am I doing wrong? (Note: the excel file cannot have a  headerrow)


string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pFilePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR:NO;\"";
            OleDbConnection conn = new OleDbConnection(connstr);
            DataTable dtTables = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            string strTablename = dtTables.Rows[0]["TABLE_NAME"].ToString();
            string strSQL = "SELECT * FROM [" + strTablename + "]";

            OleDbCommand cmd = new OleDbCommand(strSQL, conn);

            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            //At this point row count=2 which doesn't make sense




Excel-like experience - gridview focus problem



I'm creating a page where people can order several items from a list without having to press "edit" and "save" in between like you normally would in a gridview. The user writes down the quantity, and finally presses a "submit" button that saves the order.

I want the user to have a windows form (or excel) like eperience, so once the user puts in the quantity and moves on to the next item, either by TAB or by clicking on the TextBox, i make some calculations without the user beeing bothered with a full refresh or having to press a buton to execute the event, so I place the controls inside an UpdatePanel and use TextBox.TextChanged. The event runs code that calculates the sum for the row (price * quantity) and shows that in a column called "Sum", and updates a label in a fixed position with the new order total ("Total").

Any ideas on how to achieve this?

Right now I use a GridView with a templatefield for the Quantity and set the TextBox.TextChanged event to fire to make the calculations. The problem is that the focus then changes.

By using SmartNavigation or the ScriptManager.SetFocus I manage to retain focus on the TextBox that executed the Postback, but the user might have moved on to a textbox far down the gridview (thus causing the postback by leaving the previo

reading excel file problem



i have 200 rows in my excel file. im using OleDbConnection to read the excel file.

The problem is that it will read all the blank rows from row 200 onwards. Is there a configuration im missing ? or is there a way to import all rows that has data? Here's some of my code.

string excelConnectionString =
               "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + filePath + ";" +
                "Extended Properties=Excel 8.0";

OleDbConnection excelConnection =
                    new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO'");

OleDbCommand cmd = new OleDbCommand("Select * from [list$]",excelConnection);

Problem with Excel


Hi All,

I am trying to create hyperlink in Excel using below code, But it is giving me error:

Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))System.Runtime.InteropServices.COMException (0x80020005): Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))


 Dim oXL As Excel.Application
Dim oWB As Excel._Workbook
Dim oSheet As Excel._Worksheet

oXL = New Excel.Application()
oWB = DirectCast(oXL.Workbooks.Add(True), Excel._Workbook)
oSheet = DirectCast(oWB.ActiveSheet, Excel._Worksheet)

oSheet.Hyperlinks.Add(oSheet.Cells("A3"), "http://www.MySite.com", Nothing, "My Site Info", "clickhere")

It is giving the error on the above line when trying to create hyperlink.

Can you please tell me where I am doing wrong.




Excel problem

I m operning excel file using Applicaion object of Excel,InteropNow i am closing it but it doesn't release from memoryIt's process is runnig like Excel.exeHow can i release it.

Excel Connection Manager Problem

I am building a package that has 2 tasks that need to use the same excel connection manager. I use a execute sql task to dynamically build a table from the headers of the excel sheet  ,then I use an excel source component to load the data from the sheet. However when I try to edit the excel source and switch the data access mode to a variable and select the variable(for the path), when I try to close the editor I get this message 'S:\myfolder'.  It is already opened exclusively by another user, or you need permission to view its data. I need this package to access the same folder each time because the files will be placed in that folder. This package also has a branch for loading a text file into sql server. It access the same folder but uses a flatfile connection manager It looks like permissions on the folder are correct

Problem opening excel

hello everyone, i m having a serious problem, and i have been searching for days and i couldn't find a solution, my application deployed on IIS 7.5 is working very good except when trying to open excel file, i am getting an error telling me that the path is wrong or page is already used or the workbook you are trying to save already exists. to open excel m using: Dim xlApp = new Excel.application Dim xlWorkbook = new Excel.workbook Dim xlWorksheet = new Excel.worksheet   xlapp = new Excel.application xlworkbook = xlapp.workbooks.open(xxx) and here is the line of error !!!!     it seems to be a problem with the security privileges of the users, i have been told to find the excel application in Component services - COM+ and change it's security, but the problem is that i can't find the excel application in COM+ so i have tried this: Component services - mycomputer - properties - COM security - Edit default(for acces, launch and activiation permissions) and grant it for Network Service, USers and IIS_IUsers and still that did not work out.   any solution?  

data type problem in import data from excel file


Dear All,

I am importing the data from excel file using following code.

connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(strFolderFileName) & ";Extended Properties=HTML Import;"
                conn = New OleDbConnection(connstr)
                Dim strSQL As String = "SELECT * FROM [" & strWorkSheetName & "]"

                Dim cmd As New OleDbCommand(strSQL, conn)

                Dim da As New OleDbDataAdapter(cmd)

Now the problem is if a coulmn vlaue start with a number value like "15" then the other string value like "W15" in that column is ignored in the datatable.

eg. The excel column value     Column1


Problem with Linked servers from sql 2005 to Excel file


I am probably doing something stupid BUT I am creating a linked server to an excel file, I have done this on sql2005sp2x64 using the ace ole 12 provder, and replicated on another machine running sql2005sp2x32 using the jet4 provider and I am having the same problem on both.  I have turned allow inprocess option on on both providers.  I as an administrator on the machine where the database and datafile are residing have no problem accessing the linked server and the file underneath however any enduser that is not in the local administrators group gets the error   Cannot initialize the data source object of OLE DB provier "Either provider I have tried" for linked server    SQL Server Error 7303.  I have checked file permissions, and they are open to the world, I have tried both use existing authentication and use no authentication when accessing the linked server.  and I have tried endless different combinations of providers and provider strings.  I have went as far as having the enduser create a linked server to an excel file on his local machine (which he is admin on and I am not)   and he can access the file .. and I can not.  so I am just assuming there is some sort of security setting somewhere .. that I am just missing.



Problem with referencing Excel version


Apologies if this is in the wrong place and needs to be moved.

I've built a small application which takes in Excel data, manipulates it and creates a workbook with charts. The PC I first built it on has Excel 2003, 2007 and 2010 installed and I referenced the Microsoft.Office.Interop.Excel (version 11.0) dll. When I transferred to a client's PC which had only Excel 2003, I got a compile error and had to redo the reference to Excel. When I transferred again to another of the client's PCs which had only Excel 2007 installed, it again threw a compile error and I had to reference the version 12.0 Excel object library. Naturally, going back, this version didn't work on the PC with only Excel 2003 installed.

Is there a way round this, other than to build separate versions of the application for each version of Excel? Thanks in advance for any help.

SSRS 2008 export to Excel margin problem

When rendering report from SSRS 2008 with custom margins (let's say 0.5in) into Excel, margins do not export correctly, or do not export at all, thus Excel sets its default margins.

I heard in SSRS 2005 it was not a problem.

Any ideas?

export the gridview data to excel problem



i am using master page and child pages in the child page

i want to export the gridview data to excel sheet for this i use the following code


        Response.AddHeader("content-disposition", "attachment; filename=shedules.xls");

        Response.ContentType = "application/excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);




but in the gridShedules.RenderControl(htw) i got the following error but the form tag with  runat= server is already in the master page how to solve this issue

error:Control 'ctl00_ContentPlaceHolder1_grdshedules' of type 'GridView' must be placed inside a form tag with runat=server.

excel to SQL-Server Data Base, Problem


Hi Friends,
I have used following code,

Hi Friends,

if (this.FileUploadPanelToExcel .HasFile  )
                    BusinessModel.Client newClient = CreateClientFromExcel();
                     string connectionString = ConfigurationUtility.GetConnectionString();
                    ClientDataAccess.Add(newClient, connectionString);

 private BusinessModel.Client CreateClientFromExcel()
             BusinessModel.Client newClient=new BusinessModel.Client();
             string path = FileUploadPanelToExcel.PostedFile.FileName;
             OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0");
              OleDbCommand command = new OleDbCommand("select *from [sheet1$]", connection);

Problem with List Columns in Foundation 2010 when Importing from Excel


This is a pretty detailed issue. I will give you all the steps I am doing and hopefully there is a solution.

I recently updated our intranet site from WSS 3.0 to SharePoint Foundation. In WSS 3.0 I added a few of the application templates to use, including Asset Tracking. When I moved to Foundation I decided not to use those (and not sure if I can anyway) and exported the Asset Tracking data to Excel, then imported it to Sharepoint Foundation as a list.

Here is the issue I am having: when I imported from Excel all but one of the columns was created as "multiple lines of text". This means I cannot sort by these columns. I thought I could create similar columns as single lines of text, export back to Excel, copy the data, and import back. This changes the columns again to multiple lines. I even tried just typing in the data as a test and same problem. As long as there is no data, the columns will remain as single line of text; but as soon as I put data in I get this issue.

I can cofirm that these columns do not have more text than should be available in a single line. Any ideas of what I can do to make this work? I am at my wits end on this.

Thanks for any and all help.

Excel Services Application - Trusted locations problem in SharePoint Office Excel Web App


Just deployed Office Web Apps to our SharePoint 2010 environment. This environment was upgraded from a fresh deployment of SharePoint 2007 SP2. Configured all of the Application Services per http://technet.microsoft.com/en-us/library/ff431687.aspx, but I cannot open an Excel workbook, receiving the error: "This workbook cannot be opened because it is not stored in an Excel Services Application trusted location. To create an Excel Services Application trusted location, contact your system administrator."

Our farm has a single front end server and a single database server. The shared application pool is called SSP1_v14 (renamed during the upgrade from SSP1?). Our existing site had its visual style upgraded during the conversion. An in-place upgrade had been performed.

I went to Central Administration > Excel Services Application > Trusted File Locations and the default entry for address http://, Location Type: Microsoft SharePoint Foundation, Trust Children had already been created. Various blog posts on the internet indicate that this entry is all that's needed to setup a trusted location for all SharePoint sites, but it's not working here. I've tested Word document viewing with the Word Web App and that works fine.

Any ideas?

Gridview to Excel problem


I was successful in my first attempt at exporting a gridview to an excel file.
However the next attempt, has a gridview with paging, sorting and a footer. 

I found code to turn off the paging and sorting. It also shows another databind call, even with this I still get the error: RegisterForEventValidation can only be called during Render();

Can a gridview with a footer also be causing this error?  Below is my code:

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

        ' turn off paging 
        GridView1.AllowPaging = False
        GridView1.AllowSorting = False



        '  turn the paging on again 
        GridView1.AllowPaging = True
        GridView1.AllowSorting = True


Export to Excel 2007 Problem - SQL Server 2008



Hi! I did a quick test to dump data into an Excel spreadsheet. Everything worked fine, but when I created a job to do this for me and then run it, I get this error:


Date  10/8/2008 4:24:25 PM
Log  Job History (ExportClientInfoToSpreadsheet)

Step ID  1
Server  OHI0056
Job Name  ExportClientInfoToSpreadsheet
Step Name  CreateExcelClientExport
Duration  00:00:00
Sql Severity  0
Sql Message ID  0
Operator Emailed  
Operator Net sent  
Operator Paged  
Retries Attempted  0

Executed as user: OHI0056\SYSTEM. Microsoft (R) SQL Server Execute Package Utility  Version 10.0.1600.22 for 64-bit  Copyright (C) Microsoft Corp 1984-2005. All rights reserved.    Option "12.0;HDR=YES;" is not valid.  The command line parameters are invalid.  The step failed.


Here is the script of the job. Any ideas what is going on?





USE [msdb]


/****** Object: Job [ExportClientInfoT

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend