views:

1479

answers:

4

Hi,

I am using ASP.NET to read the data in the excel file. I am using a file upload control to read the file. I am able to read the data from the file in my local machine, but after deploying my code in the server, when I try to read the file from the client machine, I am getting an exception.

FileUpload1.PostedFile.FileName is throwing the exception in the server.

The exception message is:

'D:\path in client machine\MyExcel.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct. If you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted.

Please help.

Code :

<add key="OleDbConnection" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=
          FilePath ;Extended Properties=&quot;Excel 8.0;HDR=Yes;IMEX=1&quot;"/>

string OleDbConnection = 
    ConfigurationManager.AppSettings["OleDbConnection"].ToString().Replace("FilePath", 
        fileUpload.PostedFile.FileName).Trim();

Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
Excel.Workbooks xlWorkBooks = (Excel.Workbooks)xlApp.Workbooks;

Excel.Workbook wb = xlWorkBooks._Open(fileUpload.PostedFile.FileName, Type.Missing,
    false, Type.Missing, "", "", true, Excel.XlPlatform.xlWindows, "\t", true,
    false, Type.Missing, true);

    string strSheetName = ((Excel.Worksheet)wb.Sheets[1]).Name.ToString();
    xlWorkBooks.Close();
    xlApp.Quit();

   oledbCommand = new OleDbCommand();
   oledbAdapter = new OleDbDataAdapter();
   DataSet dsExcellData = new DataSet();


   oledbConnection = new OleDbConnection(OleDbConnection); 
   oledbConnection.Open();
   oledbCommand.Connection = oledbConnection;

   oledbCommand.CommandText = "Select * from [" + strSheetName + "$]"; 
   oledbAdapter.SelectCommand = oledbCommand;
   oledbAdapter.Fill(dsExcellData);
   return dsExcellData

Hi I am posting the sample code that i am having

Add a fie upload control and a button.On the button click execute the below code after selecting the file from the client machine.

string OleDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= \"FilePath\";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\""; OleDbConnection = OleDbConnection.Replace("FilePath", FileUpload1.PostedFile.FileName); Label6.Text = OleDbConnection;

        string strSheetName = "ASSET_RECV";
        OleDbConnection oledbConnection;
        OleDbCommand oledbCommand;
        OleDbDataAdapter oledbAdapter;

        oledbCommand = new OleDbCommand();
        oledbAdapter = new OleDbDataAdapter();
        DataSet dsExcellData = new DataSet();

        oledbConnection = new OleDbConnection(OleDbConnection);
        oledbConnection.Open();
        oledbCommand.Connection = oledbConnection;
        //oledbCommand.CommandText = "Select * from [{0}$]";

        oledbCommand.CommandText = "Select * from [" + strSheetName + "$]"; // i want to find this sheet name
        oledbAdapter.SelectCommand = oledbCommand;
        oledbAdapter.Fill(dsExcellData);

        oledbConnection.Close();
        GridView1.DataSource = dsExcellData.Tables[0];
        GridView1.DataBind();

1) Publish the project in IIS.Try to run the application from another machine and read the data from the excel file (from client machine).

you will get the below error .Please help.

The Microsoft Jet database engine could not find the object 'D:\FileName.xls'. Make sure the object exists and that you spell its name and the path name correctly.

A: 

You need to make sure the file exists where you say it does. The error is saying it cannot find the file specified by the path. Also make sure your spelling is correct.

Matthew Jones
Hi the file is there in that path .The file path is selected using the file upload control.SO the server is unable to trace the file from the client machine.
Jebli
+1  A: 

I think you need to save the file before you can open it. You can use:

PostedFile.SaveAs()

to save it to the server.

Did that help?

Alex
Hi,When the file is there in the client machine.Where should i save it.I just want to read the data in the file by opening it.
Jebli
Thanks you are correct.We have to save the file before reading it.
Jebli
+1  A: 

Can you post your uploading code?
Should be something like this..

<asp:FileUpload ID="batchUpload" runat="server" />
<asp:Button runat="server" ID="uploadButton" Text="Upload" OnClick="UploadButton_Click" />

protected void UploadButton_Click(object sender, EventArgs e)
  {
    // Server time out 50 mins..
    Context.Server.ScriptTimeout = 60 * 50;

    errorLabel.Style[HtmlTextWriterStyle.Color] = "Red";
    if (batchUpload.PostedFile == null || batchUpload.PostedFile.ContentLength == 0) {
      errorLabel.InnerText = "Enter a valid file";
      uploadButton.Enabled = true;
      return;
    }
    string path = XMAppSettings.UploadsPath;
    filePath = Path.Combine(path, batchUpload.FileName);
    try {
      batchUpload.SaveAs(filePath);
    } catch (HttpException exception) {
      errorLabel.InnerText = "Fatal error";
      exception.Log();
      return;
    }

Notice the batchUpload.SaveAs(filePath)
Confirm the save!

Also, since you are trying to extract data from an excel sheet I'd suggest you exploit Linq over datasets(if you are not planning to do inserts). Excel.ApplicationClass will require that you reference the excel interops

/// <summary>
  /// Summary description for ExcelHelper.
  /// </summary>
  internal sealed class ExcelHelper
  {
    private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";";

    public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)
    {
      OleDbConnection objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
      DataSet dsImport = new DataSet();
      try {
        objConnection.Open();
        DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if ((null == dtSchema) || (dtSchema.Rows.Count <= 0)) {
          throw new ArgumentNullException("No sheets");
        }
        //Reading the first sheet name from the Excel file.
        sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
        new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection).Fill(dsImport);
      } catch (Exception e) {
        e.Log();
        throw;
      } finally {
        objConnection.Close();
        objConnection.Dispose();
      }
      return dsImport.Tables[0];
    }
  }

and then do stuff like

  var table = ExcelHelper.GetDataTableFromExcelFile(fileName, ref something).AsEnumerable();
  var rollnoList = table
    .Where(x => !String.IsNullOrEmpty(x.Field<string>("Roll Number")))
    .Select(x => ExtractUser(x));
Cherian
A: 

Hi All, Thanks for the replies.I have fixed the issue.

The mistake that i did was i supplied the FileUpload1.PostedFile.FileName as a path to the excel connection string.What happens when we deploy the code in the server and try to read the excell is ,it is searching for the file in the server path.

So we need to save the file to the server before reading the file and we need to pass that server path to the excel connection string.

After reading the data from the excel you can delete the file.

But i am not sure whether there are some other work around like passing the file object as the datasource for the excel connection string.

Jebli

related questions