I am trying to find the best way of selecting an excel spreadsheet (xls and xlsx) using a fileupload control and then parsing it with filestream object and then populating a dataset.
This is my code so far which does the job but how it differs is I am saving the excel spreadsheet to a folder in my solution then querying the data using Microsoft ACE OLEDB connection.
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
//Path.GetExtension(ctrlFileUpload.PostedFile.ContentType);
string fileLocation =
Server.MapPath("~/App_Data/" + fileName);
ctrlFileUpload.SaveAs(fileLocation);
// Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
}
// Create OleDb Connection and OleD Command
using (OleDbConnection con = new OleDbConnection(connectingString))
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
//DataTable dtExcelRecords = new DataTable();
DataSet ds = new DataSet();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "Select * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
//dAdapter.Fill(dtExcelRecords);
dAdapter.Fill(ds);
//GridView1.DataSource = dtExcelRecords;
//GridView1.DataBind();
}
catch (Exception ex)
{
}
}
}
}
So to summarise I want to read the data in a spreadsheet and then bind it to a dataset but without saving the file to a physical path.
Is there a cleaner way of writing this code that I am missing. Thanks!!
I think it not possible to get data without save file to your server
If you can't save uploded file how can you give Data Source to your oleDbConnection string ??
you can delete file after finish this execution if you don't want to keep the file.
you can also refer this way https://stackoverflow.com/a/12420416/284240
Related
I have an Excel Upload in which there are columns for dates which while uploading is giving me error as
orA-01843: not a valid month while uploading excel in bulkCopy
Below is the code.
protected void btnUpload_Click(object sender, EventArgs e)
{
//Coneection String by default empty
string ConStr = "";
//Extantion of the file upload control saving into ext because
//there are two types of extation .xls and .xlsx of excel
string ext = Path.GetExtension(FileUploadIPFee.FileName).ToLower();
//getting the path of the file
string path = Server.MapPath("~/UploadData/" + FileUploadIPFee.FileName);
//saving the file inside the MyFolder of the server
FileUploadIPFee.SaveAs(path);
if (ext.Trim() == ".xls")
{
//connection string for that file which extantion is .xls
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (ext.Trim() == ".xlsx")
{
//connection string for that file which extantion is .xlsx
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//making query
string query = "SELECT * FROM [Sheet1$]";
//Providing connection
OleDbConnection conn = new OleDbConnection(ConStr);
//checking that connection state is closed or not if closed the
//open the connection
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//create command object
OleDbCommand cmd = new OleDbCommand(query, conn);
// create a data adapter and get the data into dataadapter
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
//DataSet ds = new DataSet();
DataTable dt = new DataTable();
//fill the excel data to data set
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
SaveUsingOracleBulkCopy("IPCOLO_IPFEE_CALC_MST", dt);
}
conn.Close();
// SaveUsingOracleBulkCopy("IPCOLO_IPFEE_CALC_MST", dtExcelRows);
}
public void SaveUsingOracleBulkCopy(string destTableName, DataTable dt)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString_IPCOLO"].ToString();
try
{
using (var connection = new Oracle.DataAccess.Client.OracleConnection(connectionString))
{
connection.Open();
using (var bulkCopy = new Oracle.DataAccess.Client.OracleBulkCopy(connection, Oracle.DataAccess.Client.OracleBulkCopyOptions.UseInternalTransaction))
{
bulkCopy.DestinationTableName = destTableName;
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.WriteToServer(dt); // here is the error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Data Uploaded Successfully')", true);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
I am reading excel sheet using below code but that gives blank data table.
public static DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch(Exception ex) { }
}
return dtexcel;
}
It displays empty data table as below screenshot.
you forgot few things, like OleDbConnection.Open(); and using OleDbCommand
public DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string sheetName = "Sheet1$";
string conn = string.Empty;
DataTable dt = new DataTable();
if (fileExt.CompareTo(".xlsx") != 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
using ( OleDbCommand cmd = new OleDbCommand())
{
con.Open();
try
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
dt.TableName = sheetName;
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (Exception ex) { }
}
return dt;
}
try rhis code hope it help you
protected void btn_Click(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("File/" + filename));
string CurrentFilePath = Server.MapPath("File/" + filename);
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CurrentFilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
conn.Open();
DataTable Sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [" + sht + "]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
}
}
For me working following code
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "").Replace("\\bin\\Release", "");
string fileLocation = filePath + ConfigurationManager.AppSettings["EmployeeDetailsFilePath"];
Stream inputStream = File.Open(fileLocation, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(inputStream);
reader.IsFirstRowAsColumnNames = true;
DataSet dataSet = reader.AsDataSet();
inputStream.Dispose();
reader.Dispose();
here must add reference of ExcelDataReader dll in your project.
I have set a password on my excel sheet. To unlock the worksheet, I modified my OLEDB connection string, but it didn't work. I got an error that "the source contains no dataRows", which means that it couldn't read the data from the excel file.
Before it was fine. What might be my problem?
This is my code:
public DataTable getExcelData(string fileName, string sheetName, ComboBox[] User_ComboBox)
{
this.m_comboBox = User_ComboBox;
// connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 12.0 XML;HDR=No;IMEX=1'";
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Password=xyz;Extended Properties='Excel 8.0;HDR=YES'";
string errorMessage = "";
DataTable dt = new DataTable();
try
{
string query = "SELECT * FROM [" + sheetName + "]";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, con);
dataAdapter.Fill(dt);
}
catch (Exception exp)
{
// errorCode = ErrorDefinition.ERROR_OLEDBERROR;
errorMessage = exp.Message;
}
return dt;
}
Instead of using an OleDbConnection you might consider using an Excel reading library like EPPlus to read the excel file. EPPlus supports reading password protected excel files.
You would need to implement some code to build the actual DataTable, but that should be simple enough. Just google it if you need to.
I want to import data from an Excel 2003 file, but my C# program gives error
External table is not in the expected format
I use this code:
string ExcelContentType = "application/vnd.ms-excel";
string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (fileuploadExcel.HasFile)
{
//Check the Content Type of the file
if (fileuploadExcel.PostedFile.ContentType == ExcelContentType || fileuploadExcel.PostedFile.ContentType == Excel2010ContentType)
{
try
{
//Save file path
string path = string.Concat(Server.MapPath("~/TempFiles/"), fileuploadExcel.FileName);
//Save File as Temp then you can delete it if you want
fileuploadExcel.SaveAs(path);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Excel_table";
bulkCopy.WriteToServer(dr);
lblMessage.Text = "The data has been exported succefuly from Excel to SQL";
}
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
}
Hi here i am using this to import from Excel File.Try this.Works 100%...
Here you should have a folder inside your application named as "Files" where after uploading your excel file,it will be stored and your program will read from the excel file available inside "Files" Folder.
protected void btnImport_Click(object sender, EventArgs e)
{
ArrayList alist = new ArrayList();
string connString = "";
string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
string fileBasePath = Server.MapPath("~/Files/");
string fileName = Path.GetFileName(this.fileuploadExcel.FileName);
string fullFilePath = fileBasePath + fileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
}
if (fileuploadExcel.HasFile)
{
string query = "SELECT [UserName],[Education],[Location] FROM [Sheet1$]";
using(OleDbConnection conn = new OleDbConnection(connString))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Session["griddata"] = ds.Tables[0];
grvExcelData.DataSource = Session["griddata"];
grvExcelData.DataBind();
}
}
}
Try this: Connection String
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
You can use SSIS tool( Sql server integration services)
create connection to excel sheet then add source and destination
your source will be excel sheet and your destination will be Database table
ok?
if you need more info please tell me...
I have Excel files that are in 2000 & 2003 format. I need to import them via C# code into an access DB. I have written a method to read the file into a data table. No matter which connection string i use (I have checked the other posts on this topic) I continue to get "Table is not in the correct format" error. Can someone please explain to me what I am doing wrong.
public static DataSet ParseExcel(string excelFile)
{
string sheetName = Path.GetFileNameWithoutExtension(excelFile);
string excelQuery = #"SELECT * FROM [" + sheetName + "]";
string excelConnctionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "" + excelFile + "" +
#";Extended Properties=" + "" + #"Excel 8.0;HDR=Yes;" + "";
if(File.Exists(excelFile))
{
var myConnection = new OleDbConnection(excelConnctionString);
myConnection.Open();
var myCommand = new OleDbDataAdapter(excelQuery, excelConnctionString);
myCommand.TableMappings.Add("Table", "TestTable");
var dtSet = new DataSet();
myCommand.Fill(dtSet);
myConnection.Close();
return dtSet;
}
return null;
}
Go through this code example carefully and try to understand the work flow. You will get it real easy to write any kind programs for accessing excel data according to your requirements.
1.Here I just have a Upload Field in order to select the Excel File in .aspx file
<asp:FileUpload ID="Upload_File" runat="server" />
<asp:Button ID="Upload_Button" runat="server" Text="Upload" onclick="btnUpload_Click"/>
<asp:GridView ID="Gridview_Name" runat="server">
</asp:GridView>
Now lets see what happens in code behind file (.aspx.cs file)
protected void Upload_Button_Click(object sender, EventArgs e)
{
string connectionString = "";
if (Upload_File.HasFile) // checking whether file is selected to be uploaded
{
//getting name of the file
string fileName = Path.GetFileName(Upload_File.PostedFile.FileName);
//getting extension of the file (for checking purpose - which type .xls or .xlsx)
string fileExtension = Path.GetExtension(Upload_File.PostedFile.FileName);
string fileLocation = Server.MapPath("" + fileName); //exact location of the excel files
Upload_File.SaveAs(fileLocation);
//Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create OleDB Connection and OleDb Command
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
//cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
Gridview_Name.DataSource = dtExcelRecords;
GridView_Name.DataBind();
}
else
{
Response.Write("Please Select a File to extract data ");
}
}
Step by Step Explanation :
We get the file name, extension, location .
And check it is the type (.xls or .xlsx - particularly for excels of 2003 or other formats).
Set connection strings according to the previous step.
Open oledb connection
Create the necessary data adapter and data table
open the connection
store the current table( where the data from excel is stored) in a datatable instance
Store the name of the sheet in astring by getting it from the current table
Fill the data adapter object(dAdapter) with the our data table (dtExcelRecords)
close the connection
Set datasource for the grid as out data table.
Bind it with our grid.
...And We are done!
Hope it helps.
Try this
OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";