good afternoon,
I am trying to create a method that returns the data of an excel file to call it through a FileDialog for example ... Here is my code:
public static DataSet MtdGetExcel(string prtlocalFile)
{
string sDBstrExcel = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=0\"", prtlocalFile);
OleDbConnection conexaoExcel = new OleDbConnection(sDBstrExcel);
conexaoExcel.Open();
DataTable dt = conexaoExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataSet output = new DataSet();
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString(); //Obtém o nome da planilha corrente
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conexaoExcel); //Obtém todas linhas da planilha corrente
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet); //Copia os dados da planilha para o DataTable
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
conexaoExcel.Close();
return output;
}
But when I call the method does not return anything in the DataGridView...
public void testeImportExcel()
{
try
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Selecione o relatório do Detran";
fdlg.InitialDirectory = #"c:\";
//string endereco = fdlg.FileName;
//txtNomeArquivo.Text = fdlg.FileName;
fdlg.Filter = "Excel File (*.xlsx)|*.xlsx";
//fdlg.Filter = "Excel File (*.csv)|*.csv";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
myDtGridView.DataSource = MtdGetExcel(fdlg.FileName);
myDtGridView.AutoGenerateColumns = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Result:
Can you help me?
Here is my exact method that I have in production:
public DataTable ReadExcel(string fileName, string TableName)
{
DataTable dt = new DataTable();
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0\"");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + TableName, conn);
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (!reader.IsClosed)
{
dt.Load(reader);
}
}
finally
{
conn.Close();
}
return dt;
}
I'm sure just by looking at it you can tell- this method takes in the fileName (or file path) of the Excel you're wanting to read from. Creates the connection string and command. Excel will be read like a database and its worksheets will be read like tables. TableName is the name of the worksheet (table). This method returns a DataTable that can be added to a DataSet if needed.
Related
I made a program to open Excel file.
There are exist data page and blank page.
Can I add only the pages where the data exists in the combo box?
Can I use ButtonEvent to view only pages that contain data?
string filePath = openFileDialog1.FileName;//파일 경로 가져오기
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
//string connectionString = string.Empty;
string sheetName = string.Empty;
using (OleDbConnection con = new OleDbConnection(ConnectStr()))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
public string ConnectStr()
{
string filePath = openFileDialog1.FileName;
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
string connectionString = string.Empty;
string sheetName = string.Empty;
switch (fileExtension)
{
case ".xls": //Excel 97-03버전
connectionString = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07이상 버전
connectionString = string.Format(Excel16ConString, filePath);
break;
}
return connectionString;
}
I don't really get what is this. But I beg you need to show only specific sheet from spreadsheet correct me if i'm wrong.
There is a SQL commend that we can query from the specific sheet.
try
{
this.txtImportFilePath.Text = opd.FileName;
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("Select * From [Sheet1$]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
DataView dvEmp = new DataView(dsXLS.Tables[0]);
trnxlistDataview.DataSource = dvEmp;
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
//matching columns
//SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
//SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
I know I need to add something like:
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
but I am not sure where I am supposed to add it in the above code
The column mappings are to be added to the bulkCopy.ColumnsMappings collection:
var mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
bulkCopy.ColumnMappings.Add(mapping1);
You do the mapping before you execute the WriteToServer call.
The MSDN documentation of SqlBulkCopyColumnMapping has further documentation and an example.
I am able to import excel sheet data into sql server table but i am unable to implement column mapping. please help.
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
con.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
con.Close();
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try { SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
Error:
No value given for one or more required parameters.
You created but didn't add the mappings to SqlBulkCopy.
Add the code below:
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
What is efficient & simplest way to bind data from excel sheet to repeater or GridView.
I think it is easy to create OleDbDataAdapter and creating a DataSet will do the job.
You can easily bind a DataSet to gridview
eg
var conn = ("Provider=Microsoft.Jet.OLEDB.4.0;" +
("Data Source=add file path here;" +
"Extended Properties=\"Excel 8.0;\""));
var query = "SELECT table from [sheet1$]";
var adpterObj = new OleDbDataAdapter(SSQL, conn);
var ds = new DataSet();
adpterObj.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
You should read data from Excel using any one library (OLEDB Connection, COM Object or any other) and after Puts result to any .Net objects (DataSet, DataTable) according to your requirement. then bind DataSet to your Repeater.
maybe this link will solve your problem
click me
public static DataSet ImportExcelXLS(string FileName, bool hasHeaders) {
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn)) {
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow schemaRow in schemaTable.Rows) {
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_")) {
try {
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
} catch (Exception ex) {
throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
}
}
}
}
return output;
}
First we have to browse
void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Excel files (*.xls)|*.xls";
fileDialog.InitialDirectory = "C:";
fileDialog.Title = "Select a Excel file";
if (fileDialog.ShowDialog() == DialogResult.OK)
txtMsg.Text = fileDialog.FileName;
if (string.IsNullOrEmpty(txtMsg.Text))
return;
}
Note: txtMsg.Text = fileDialog.FileName; //here file name keeping in one text box
Then we can upload excel sheet to gridview...
private void btnUpload_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtMsg.Text))
{
InsertBuyBackExceldata(txtMsg.Text);
}
}
Here we can call InsertBuyBackExceldata method
void InsertBuyBackExceldata(string filePath)
{
if (buyBackServiceProxyController == null)
buyBackServiceProxyController = new ProxyController();
buyBackServiceServiceProxy = buyBackServiceProxyController.GetProxy();
ListBuyBackrequest = new List();
String[] a= GetExcelSheetNames(filePath); // This method for get sheet names
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", filePath);
//string a=filePath.
String sheetName = a[0];
var adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, sheetName );
DataTable data = ds.Tables[sheetName ];
BindGrid(data);
}
here I am calling a method to get Sheet name.
private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
//Excel Uploading to Gridview
void BindGrid(DataTable Data)
{
try
{
// Adding one check box
DataGridViewCheckBoxColumn chkSelection = new DataGridViewCheckBoxColumn();
chkSelection.Name = "Selection";
dgItemsForBuyBackGrid.Columns.Add(chkSelection);
int intCount = Data.Rows.Count;
if (i==true)
{
if (intCount > 0)
{
ExcelGrid.DataSource = Data;
ExcelGrid.BindPage();
}
else
{
ExcelGrid.DataSource = null;
ExcelGrid.BindPage();
return;
}
// Here I am setting Grid colomns properties this name should equal to Excel //column names.
ExcelGrid.Columns["BI"].ReadOnly = true;
ExcelGrid.Columns["AAA"].ReadOnly = true;
ExcelGrid.Columns["AAB"].ReadOnly = true;
ExcelGrid.Columns["AAC"].ReadOnly = true;
ExcelGrid.Columns["AAD"].ReadOnly = true;
ExcelGrid.Columns["AAE"].ReadOnly = true;
ExcelGrid.Columns["AAF"].ReadOnly = true;
ExcelGrid.Columns["AAG"].ReadOnly = false;
}
else
{
// Some Code
}
}
catch (Exception ex)
{
}
}
}
}
Excel 2007 and other versions Uploading to Gridview in .Net.
Steps:
1) AccessDatabaseEngine.exe --> (Install)
And some code changes from above code.
2) Browse Click
private void btnBrowse_Click(object sender, EventArgs e)
{
-------
fileDialog.Filter ="Excel files (*.xls;*xlsx;*xlsb)|*.xls;*xlsx;*xlsb";
// Show those extentional files.
--------------
}
3) Process Click
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
Thank You :)
Am having one excel file with 2 different worksheets as fundmodelrate and project.Now I want to import these 2 different sheet values into 2 different sql tables(k2_fundmodelrate,k2_project).I can able to do import only if am working with 1 sheet and and 1 table,but I want two sheets values to be imported on two tables at the same time on button click event.
My code below:
private String strConnection = "Data Source=kuws4;Initial Catalog=jes;User ID=sa;Password=******";
protected void btnSend_Click(object sender, EventArgs e)
{
string path = fileuploadExcel.PostedFile.FileName;
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\fmr.xls;Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [FundModelRate$]", excelConnection);
//OleDbCommand cmd1 = new OleDbCommand("Select * from [FundModelRate$], [Project$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "K2_FundModelRate";
// sqlBulk.DestinationTableName = "K2_Project";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
I think the only way is to loop through your two sheets.
Have a look at This post. This will help you get the sheet names.
When you have the sheet names, you can then just loop through them and then load them into SQL.
Maybe this can help you:
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string excelConnection = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
excelConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
objConn = new OleDbConnection(excelConnection);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
for(int j=0; j < excelSheets.Length; j++)
{
OleDbCommand cmd = new OleDbCommand("Select * from " + excelSheets[j], excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "YourDestinationTableName";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
Note: Not tested
public void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "test_data";//sql table name
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if havedifferent
string myexceldataquery = "select * from [Sheet1$]";
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 = "server=ServerName;user id=sa;password=sa;database=Databasename;connection reset=false";
//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);
DataTable dt = new DataTable();
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
oledbconn.Close();
}
catch (Exception)
{
throw;
}
}
/*---------- call that file on buttonclick through OpenDialogBox--------*/
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
importdatafromexcel(strfilename);
}
Console.WriteLine(result);
MessageBox.Show("Exported to SQL successfully");
}