How to retrieve data from Excel file using OleDbConnection - c#

the thing is that I need to select only 2 columns from the data in Excel, so i went on using sql for retrieving the data from the Excel file. But this time i keep getting "failed to create file" error and this happens when i try to open my connection. Why is it trying to create a file ?
my code:
public void ReadExcelFile()
{
string connectionString = string.Format(ConfigurationManager.ConnectionStrings["ExcelConnection"].ConnectionString.Replace("'", "\""), "#C:/Temp/Copy.xlsx");
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
string sqlCmd = "SELECT * FROM [Ark1$]";
using (OleDbCommand command = new OleDbCommand(sqlCmd, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.ToString());
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("ERROR in ReadExcelFile() method. Error Message : " + exception.Message);
}
}
}
can anyone help me with this ?

** EDITED **
Test it like this:-
string filename = "#C:\Temp\Copy.xlsx";
OleDbConnection con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filename + ";Extended Properties=\Excel 8.0;HDR=YES;IMEX=1\"");

To configure OleBConnection for read Excel file try this:
string filename = "#C:\Temp\Copy.xlsx";
OleDbConnection connection =new OleDbConnection(
"provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+filename+"';"+
"Extended Properties=Excel 8.0;");

Related

File upload not working in ASP.NET When Deployed

This code is working fine on localhost but when I try to run this code in server its not working..can anyone tell me what's wrong?
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.;Initial Catalog=EkkiDB;Integrated Security=TRUE";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [SurveyDate],[DealerName],[Model],[HP],[Quantity],[ID] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Import_Survey";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath( FileUpload fileUploadControl)
{
//string filePath = Server.MapPath(fileUploadControl.FileName);
// string filePath = Path.Combine(saveDirectory);
string filePath = Server.MapPath("~/xl/") + Path.GetFileName(fileUploadControl.PostedFile.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
Where is your destination directory? If it's not under IIS control check that your anonymous user account has write access to it.

I get an eror in uploading excel db file to sql server in winforms C#

I am trying to create an Excel data uploader to upload Excel files to SQL Server using Winforms in C#.
After bulkcopy.WriteToServer(dr); I get this error :
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
The Connection for viewing your linked Microsoft Excel worksheet was lost.
I got information about regedit here and tried to follow it but still the same error:
class Pass
{
static string _excelfilepath;
public static string excelfilepath { get { return _excelfilepath; } set { _excelfilepath = value; } }
public void importdatafromexcel()
{
//declare variables - edit these based on your particular situation
string ssqltable = "tStudent";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select idnum,fname,gname,mname,coacro,year,yrstat,sex,stat,telno,addr1,addr2,addr3,dbirth,mothname,fathname,civstat,religion,hssch from [masterlist$]";
try
{
//create our connection strings
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + _excelfilepath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = #"Data Source=LYNDON-PC\LYNDON;Initial Catalog=trial;Persist Security Info=True;User ID=sa;Password=14323531";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
What does the error mean and get the code to upload my Excel file to my table in my database in SQL Server...
I think you should use
bulkcopy.WriteToServer(dr);
instead of using
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}

Upload an excel File to Database

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...

Returning a OleDbDataReader from a function

I am trying to return OleDbDataReader from a function. I search on internet and I found some help and I create a code
public IEnumerable<IDataRecord> ImportXLS(string path)
{
string connString = "";
string strFileType = ".xlsx";
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
using (IDataReader xlsReader = cmd.ExecuteReader())
{
while (xlsReader.Read())
{
yield return (IDataReader)xlsReader;
}
}
conn.Close();
}
This is OK It Return xlsReader, and I try to catch this xlsReader by
public string UploadFile(string tPath, string FileName)
{
string msg = "";
FileImportModule.FileImport OFileImport = new FileImportModule.FileImport();
SqlDataReader reader = (SqlDataReader)OFileImport.ImportXLS(tPath);
var context = new MountSinaiEntities1();
string tableName = context.Tables.Find(1).tableName;
var tableFieldList = from a in context.TablesFields
where a.tableId == 1
select a.fieldName;
//1- SQL Bulk Copy
try
{
SqlConnection con = new SqlConnection(#"Data Source=abhishek-pc;Initial Catalog=MountSinai;User ID=sa;Password=abhi");
con.Open();
SqlBulkCopy bulkcopy = new SqlBulkCopy(con);
{
bulkcopy.DestinationTableName = tableName;
bulkcopy.WriteToServer(reader);
}
con.Close();
}
catch (Exception e)
{
//Handle Exception
}
}
but the error occur
Unable to cast object of type 'd__0' to type
'System.Data.SqlClient.SqlDataReader'
What is the Solution for that problem? Any alternative to use it as reader object...
You are returning a type of IEnumerable<IDataRecord>, so you cannot cast it to an SqlDataReader.
Just return xlsReader (making sure to dispose it properly) if that is what you want. Otherwise, just use the data you are returning.

Reading a spreadsheetl file from fileupload control into filestream

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

Categories

Resources