Insert data from Excel to database - c#

I have a excel sheet, what I want is I want to upload the excel sheet record into the database table. But in that
Emp_Code is identity
Qns is Identity
I tried like below,
protected void btnUpload_Click(object sender, EventArgs e)
{
DataTable dtExcel = new DataTable();
dtExcel.Clear();
string StrCount = String.Empty;
string connString = "";
HttpPostedFile File = FileUpload1.PostedFile;
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
string Filename = path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1);
path = Server.MapPath(#"~/Excels/" + "/" + Filename.ToString());
File.SaveAs(path);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
// connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.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 [Sheet 1$]";
OleDbConnection conn = new OleDbConnection(connString);
conn.Close();
if (conn.State == System.Data.ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter daExcel = new OleDbDataAdapter(cmd);
StringBuilder StrPubBldg = new System.Text.StringBuilder();
XmlWriter xw = XmlWriter.Create(StrPubBldg);
string ExcelfileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
xw.WriteStartElement("DocumentElement");
{
xw.WriteStartElement("Emp_Eval_Proc_hdr");
xw.WriteElementString("mkey", (0 + 1).ToString());
xw.WriteElementString("Emp_Code", dtExcel.Rows[1][("Emp Code")].ToString()); // Identity
xw.WriteElementString("Emp_Name", dtExcel.Rows[2][("Emp Name")].ToString());
xw.WriteElementString("Qns_No", dtExcel.Rows[3][("Qns No")].ToString()); // Identity
xw.WriteElementString("Self", dtExcel.Rows[0][("Self")].ToString());
xw.WriteElementString("AS1", dtExcel.Rows[0][("AS1")].ToString());
}
but getting error as
There is no row at position 1.
How to do that ??

dtExcel, you created a new DataTable then immediately clear it then attempt to access data. What you should do is follow this conceptual model. It does not have to be exact, the principle is to load data into the smallest container which for this is a DataTable, check if there are rows then iterate as needed.
Removed first code sample, replaced with new one as per request by poster
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Xml;
namespace Example
{
/// <summary>
/// Create instance of this class,
/// pass in file name and if excel sheet has headers e.g. YES or NO
/// execute Work method, is currently incomplete
/// </summary>
public class StackOverFlowDemo
{
private string CreateConnectionString(string FileName, string Header)
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
if (System.IO.Path.GetExtension(FileName).ToUpper() == ".XLS")
{
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.Add("Extended Properties", string.Format("Excel 8.0;IMEX=2;HDR={0};", Header));
}
else
{
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.Add("Extended Properties", string.Format("Excel 12.0;IMEX=2;HDR={0};", Header));
}
Builder.DataSource = FileName;
return Builder.ConnectionString;
}
public string ConnectionString { get; set; }
public StackOverFlowDemo(string FileName, string Header)
{
ExcelTable = new DataTable();
CreateConnectionString(FileName, Header);
LoadData();
}
public DataTable ExcelTable { get; set; }
public void LoadData()
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = ConnectionString })
{
cn.Open();
using (OleDbCommand cmd = new OleDbCommand { CommandText = "SELECT * FROM [Sheet 1$]", Connection = cn })
{
OleDbDataReader dr = cmd.ExecuteReader();
ExcelTable.Load(dr);
}
}
}
public void Work()
{
StringBuilder StrPubBldg = new System.Text.StringBuilder();
XmlWriter xw = XmlWriter.Create(StrPubBldg);
// continue logic
}
}
}

Related

show Excel data from another to main application class and show in Datagridview and in combobox

I got a large .xls file which contain many columns including city name population name etc.For my code purpose I only extract the city name and population number from this excell file. I made another class with a method which will do the modification of .xls file.Now in the main Form1.cs I want to show that value at first in datagridview table as two column Like city and population and then from datagridview I want to show the city name in combobox list. I wrote a code for this. But it is showing a lot of error.
To get the excel data I wrote the following code
public class Data
{
public string DataService(DataTable data)//showing error
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "POI_List");
System.IO.Directory.CreateDirectory(folderName);
string SavedfileName = "POI_list.json";
var Saving_path = Path.Combine(folderName, SavedfileName);
string fileName = "Zensus_Gemeinden_org.xlsx";
var path = Path.Combine(startPath, fileName);
String name = "Gemeinden_31.12.2011_Vergleich";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 10000", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
//DataTable data = new DataTable();
sda.Fill(data);
string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, Place_Json);
return data;//showing error
}
}
}
Now to get this value from main class in datagrid view and combobox I wrote following code
public partial class Form1 : Form
{
private readonly Data _DataService;// showing error
public Form1()
{
_DataService=new Data();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = //here I want to set data from DataService method);
for (int i = 0; i < data.Rows.Count; i++)//showing error for 'for'
{
comboBox1.Items.Add(data.Rows[i]["City"]);
}
}
}
DataService method signature is public string DataService(DataTable data).
But you trying to return DataTable
EDIT:
Just modify your method:
public DataTable DataService()
{
var data = new DataTable();
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "POI_List");
System.IO.Directory.CreateDirectory(folderName);
string SavedfileName = "POI_list.json";
var Saving_path = Path.Combine(folderName, SavedfileName);
string fileName = "Zensus_Gemeinden_org.xlsx";
var path = Path.Combine(startPath, fileName);
String name = "Gemeinden_31.12.2011_Vergleich";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 10000", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
//DataTable data = new DataTable();
sda.Fill(data);
string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, Place_Json);
return data;
}
}
public partial class Form1 : Form
{
private readonly Data _data;
public Form1()
{
_data = new Data();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dataTable = _data.DataService()
dataGridView1.DataSource = dataTable ;
for (int i = 0; i < dataTable.Rows.Count; i++)//showing error for 'for'
{
comboBox1.Items.Add(dataTable.Rows[i]["City"]);
}
}
}

How to replace all apostrophes in an excel sheet with double apostrophes

I have to export excel sheet to ms sql database table. For that I used oledb connection . It works well. But any cell value containing apostrophes(example : cell 1 value is - divya's ) shows an error “Unclosed quotation mark after the character string” .
I found that To insert single quote or apostrophe data in database we need to use two consecutive single quotes or apostrophes in data. How can it make possible in excel sheet ?
protected void btnSend_Click(object sender, ImageClickEventArgs e) //upload QB
{
SqlConnection con = obj.getcon();
string filename = Path.GetFileName(fileuploadExcel.FileName);
int fileSize = fileuploadExcel.PostedFile.ContentLength;
if ((Path.GetExtension(filename) == ".xlsx" || Path.GetExtension(filename) == ".xls") && (fileSize <= (1.049e+6)))
{
string excel_file = "my_excel_file";
var path1 = Server.MapPath("~/personal/" + excel_file + "");
var directory = new DirectoryInfo(path1);
if (directory.Exists == false)
{
directory.Create();
}
fileuploadExcel.SaveAs(path1 + "\\" + filename);
string filepath = path1 + "\\" + filename;
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [Name],[Address] from [mysheet$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
string name = "";
string address = "";
while (dReader.Read())
{
name = valid(dReader, 0);
address = valid(dReader, 1);
insertdataintosql(name,address);
}
excelConnection.Close();
}
else
{
Label5.Visible = true;
Label5.Text = " Only Files Having .xlsx or.xls format and less than 1MB size can be uploaded**";
}
}
protected string valid(OleDbDataReader myreader, int stval)
{
//if any columns are found null then they are replaced by zero
object val = myreader[stval];
if (object.ReferenceEquals(val, DBNull.Value))
{
return Convert.ToString(0);
}
else
{
return val.ToString();
}
}
public void insertdataintosql(string name,string address,)
{ SqlConnection conn = obj.getcon();
conn.Open();
string query = "insert into sample_test(name,address) values('" + name + "','"+address+ "')";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
In your valid function:
Instead of
return val.ToString();
use:
return val.ToString().Replace("'","''");

No value given for one or more required Parameter OLEDB Exception

Previously My Code is working Correctly but now it is throwing the error :
No value given for one or more required Parameter OLEDB Exception
Code:
string excelConnectionString = string.Empty;
OleDbConnection excelConnection;
try
{
if (Request.Files["FileUpload"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload"].FileName);
String fileName = System.IO.Path.GetFileName(Request.Files["FileUpload"].FileName);
if (extension == ".xls" || extension == ".xlsx")
{
string currentPath = System.IO.Path.GetFullPath(Request.Files["FileUpload"].FileName);
{
string mappedUploadPath = string.Format("{0}\\{1}", Server.MapPath("~/Content/UploadedFolder"), fileName);
if (System.IO.File.Exists(mappedUploadPath))
System.IO.File.Delete(mappedUploadPath);
Request.Files["FileUpload"].SaveAs(mappedUploadPath);
// Create connection string to Excel work book
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mappedUploadPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
//Creating an entityconnection
using (EntityConnection sqlConnectionString =
new EntityConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
OleDbDataReader dReader;
//Create OleDbCommand to fetch data from Excel
//PromotionMaster
OleDbCommand cmd = new OleDbCommand("Select [SKU],[SupplierId],[Price],[Validity],[LastUpdated],[EnteredBy],[Quantity],[CrediteTermId],[Approved],[DeliveryDate],[ETA],[CommModeId] from [Sheet1$]", excelConnection);
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulkPromotionMaster = new SqlBulkCopy(((SqlConnection)sqlConnectionString.StoreConnection).ConnectionString);
sqlBulkPromotionMaster.DestinationTableName = "TempPriceList";
sqlBulkPromotionMaster.ColumnMappings.Add("SKU", "SKU");
sqlBulkPromotionMaster.ColumnMappings.Add("SupplierId", "SupplierId");
sqlBulkPromotionMaster.ColumnMappings.Add("Price", "Price");
sqlBulkPromotionMaster.ColumnMappings.Add("Validity", "Validity");
sqlBulkPromotionMaster.ColumnMappings.Add("LastUpdated", "LastUpdated");
sqlBulkPromotionMaster.ColumnMappings.Add("EnteredBy", "EnteredBy");
sqlBulkPromotionMaster.ColumnMappings.Add("Quantity", "Quantity");
sqlBulkPromotionMaster.ColumnMappings.Add("CrediteTermId", "CrediteTermId");
sqlBulkPromotionMaster.ColumnMappings.Add("Approved", "Approved");
sqlBulkPromotionMaster.ColumnMappings.Add("DeliveryDate", "DeliveryDate");
sqlBulkPromotionMaster.ColumnMappings.Add("ETA", "ETA");
sqlBulkPromotionMaster.ColumnMappings.Add("CommModeId", "CommModeId");
sqlBulkPromotionMaster.WriteToServer(dReader);
TempData["alertMessage"] = "Data Stored Successfully of PromotionMaster";
excelConnection.Close();
}
}
}
}
return RedirectToAction("LoadPriceExcel");
}
catch (Exception e)
{
GC.Collect();
TempData["alertMessage"] = "Exception Occured";
return RedirectToAction("LoadPriceExcel");
}
}
dReader = cmd.ExecuteReader(); here it is throwing exception No Value is given for one or more required parameter.
All fields in Excel exactly match with table.
Previously it was working now it is throwing error.
Check if your first row (A1:ZZ1) have the headers of the table.

Best /Fastest way to read an Excel Sheet into a DataTable?

I'm hoping someone here can point me in the right direction - I'm trying to create a fairly robust utility program to read the data from an Excel sheet (may be .xls OR .xlsx) into a DataTable as quickly and leanly as possible.
I came up with this routine in VB (although I'd be just as happy with a good C# answer):
Public Shared Function ReadExcelIntoDataTable(ByVal FileName As String, ByVal SheetName As String) As DataTable
Dim RetVal As New DataTable
Dim strConnString As String
strConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & FileName & ";"
Dim strSQL As String
strSQL = "SELECT * FROM [" & SheetName & "$]"
Dim y As New Odbc.OdbcDataAdapter(strSQL, strConnString)
y.Fill(RetVal)
Return RetVal
End Function
I'm wondering if this is the best way to do it or if there are better / more efficent ways (or just more intelligent ways - Maybe Linq / native .Net providers) to use instead?
ALSO, just a quick and silly additional question - Do I need to include code such as y.Dispose() and y = Nothing or will that be taken care of since the variable should die at the end of the routine, right??
Thanks!!
If you want to do the same thing in C# based on Ciarán Answer
string sSheetName = null;
string sConnection = null;
DataTable dtTablesList = default(DataTable);
OleDbCommand oleExcelCommand = default(OleDbCommand);
OleDbDataReader oleExcelReader = default(OleDbDataReader);
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Test.xls;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName)) {
oleExcelCommand = oleExcelConnection.CreateCommand();
oleExcelCommand.CommandText = "Select * From [" + sSheetName + "]";
oleExcelCommand.CommandType = CommandType.Text;
oleExcelReader = oleExcelCommand.ExecuteReader();
nOutputRow = 0;
while (oleExcelReader.Read())
{
}
oleExcelReader.Close();
}
oleExcelConnection.Close();
here is another way read Excel into a DataTable without using OLEDB
very quick
Keep in mind that the file ext would have to be .CSV for this to work properly
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
csvData = new DataTable(defaultTableName);
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[]
{
tableDelim
});
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == string.Empty)
{
fieldData[i] = string.Empty; //fieldData[i] = null
}
//Skip rows that have any csv header information or blank rows in them
if (fieldData[0].Contains("Disclaimer") || string.IsNullOrEmpty(fieldData[0]))
{
continue;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
I have always used OLEDB for this, something like...
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
The ACE.OLEDB provider will read both .xls and .xlsx files and I have always found the speed quite good.
public DataTable ImportExceltoDatatable(string filepath)
{
// string sqlquery= "Select * From [SheetName$] Where YourCondition";
string sqlquery = "Select * From [SheetName$] Where Id='ID_007'";
DataSet ds = new DataSet();
string constring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
OleDbConnection con = new OleDbConnection(constring + "");
OleDbDataAdapter da = new OleDbDataAdapter(sqlquery, con);
da.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
This seemed to work pretty well for me.
private DataTable ReadExcelFile(string sheetName, string path)
{
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = path;
string fileExtension = Path.GetExtension(Import_FileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [" + sheetName + "$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
return dt;
}
}
}
}
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy read excel file to DataTable and you can import excel file to sql server database (use SqlBulkCopy). ExcelDataReader reads very fast. On my machine 10000 records less 3 sec and 60000 less 8 sec.
Read to DataTable example:
class Program
{
static void Main(string[] args)
{
var dt = new DataTable();
using (var reader = new ExcelDataReader(#"data.xlsx"))
dt.Load(reader);
Console.WriteLine("done: " + dt.Rows.Count);
Console.ReadKey();
}
}
I found it pretty easy like this
using System;
using System.Data;
using System.IO;
using Excel;
public DataTable ExcelToDataTableUsingExcelDataReader(string storePath)
{
FileStream stream = File.Open(storePath, FileMode.Open, FileAccess.Read);
string fileExtension = Path.GetExtension(storePath);
IExcelDataReader excelReader = null;
if (fileExtension == ".xls")
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (fileExtension == ".xlsx")
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
var test = result.Tables[0];
return result.Tables[0];
}
Note: you need to install SharpZipLib package for this
Install-Package SharpZipLib
neat and clean! ;)
This is the way to read from excel oledb
try
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
string strHeader7 = "";
strHeader7 = (hdr7) ? "Yes" : "No";
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fn + ";Extended Properties=\"Excel 12.0;HDR=" + strHeader7 + ";IMEX=1\"");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + wks + "$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dgv7.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
The below code is tested by myself and is very simple, understandable, usable and fast.
This code, initially takes all sheet names, then puts all tables of that excel file in a DataSet.
public static DataSet ToDataSet(string exceladdress, int startRecord = 0, int maxRecord = -1, string condition = "")
{
DataSet result = new DataSet();
using (OleDbConnection connection = new OleDbConnection(
(exceladdress.TrimEnd().ToLower().EndsWith("x"))
? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + exceladdress + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
: "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + exceladdress + "';Extended Properties=Excel 8.0;"))
try
{
connection.Open();
DataTable schema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in schema.Rows)
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
string s = drSheet["TABLE_NAME"].ToString();
if (s.StartsWith("'")) s = s.Substring(1, s.Length - 2);
System.Data.OleDb.OleDbDataAdapter command =
new System.Data.OleDb.OleDbDataAdapter(string.Join("", "SELECT * FROM [", s, "] ", condition), connection);
DataTable dt = new DataTable();
if (maxRecord > -1 && startRecord > -1) command.Fill(startRecord, maxRecord, dt);
else command.Fill(dt);
result.Tables.Add(dt);
}
return result;
}
catch (Exception ex) { return null; }
finally { connection.Close(); }
}
Enjoy...
''' <summary>
''' ReadToDataTable reads the given Excel file to a datatable.
''' </summary>
''' <param name="table">The table to be populated.</param>
''' <param name="incomingFileName">The file to attempt to read to.</param>
''' <returns>TRUE if success, FALSE otherwise.</returns>
''' <remarks></remarks>
Public Function ReadToDataTable(ByRef table As DataTable,
incomingFileName As String) As Boolean
Dim returnValue As Boolean = False
Try
Dim sheetName As String = ""
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & incomingFileName & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
Dim tablesInFile As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
oleExcelConnection = New OleDbConnection(connectionString)
oleExcelConnection.Open()
tablesInFile = oleExcelConnection.GetSchema("Tables")
If tablesInFile.Rows.Count > 0 Then
sheetName = tablesInFile.Rows(0)("TABLE_NAME").ToString
End If
If sheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
'Determine what row of the Excel file we are on
Dim currentRowIndex As Integer = 0
While oleExcelReader.Read
'If we are on the First Row, then add the item as Columns in the DataTable
If currentRowIndex = 0 Then
For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
Dim currentColumnName As String = oleExcelReader.Item(currentFieldIndex).ToString
table.Columns.Add(currentColumnName, GetType(String))
table.AcceptChanges()
Next
End If
'If we are on a Row with Data, add the data to the SheetTable
If currentRowIndex > 0 Then
Dim newRow As DataRow = table.NewRow
For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
Dim currentColumnName As String = table.Columns(currentFieldIndex).ColumnName
newRow(currentColumnName) = oleExcelReader.Item(currentFieldIndex)
If IsDBNull(newRow(currentFieldIndex)) Then
newRow(currentFieldIndex) = ""
End If
Next
table.Rows.Add(newRow)
table.AcceptChanges()
End If
'Increment the CurrentRowIndex
currentRowIndex += 1
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
returnValue = True
Catch ex As Exception
'LastError = ex.ToString
Return False
End Try
Return returnValue
End Function
Use the below snippet it will be helpfull.
string POCpath = #"G:\Althaf\abc.xlsx";
string POCConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + POCpath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection POCcon = new OleDbConnection(POCConnection);
OleDbCommand POCcommand = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter POCCommand = new OleDbDataAdapter("select * from [Sheet1$] ", POCcon);
POCCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
I've used this method and for me, it is so efficient and fast.
// Step 1. Download NuGet source of Generic Parsing by Andrew Rissing
// Step 2. Reference this to your project
// Step 3. Reference Microsoft.Office.Interop.Excel to your project
// Step 4. Follow the logic below
public static DataTable ExcelSheetToDataTable(string filePath) {
// Save a copy of the Excel file as CSV
var xlApp = new XL.Application();
var xlWbk = xlApp.Workbooks.Open(filePath);
var tempPath =
Path.Combine(Environment
.GetFolderPath(Environment.SpecialFolder.UserProfile)
, "AppData"
, "Local",
, "Temp"
, Path.GetFileNameWithoutExtension(filePath) + ".csv");
xlApp.DisplayAlerts = false;
xlWbk.SaveAs(tempPath, XL.XlFileFormat.xlCSV);
xlWbk.Close(SaveChanges: false);
xlApp.Quit();
// The actual parsing
using (var parser = new GenericParserAdapter(tempPath)) {
parser.FirstRowHasHeader = true;
return parser.GetDataTable();
}
}
Generic Parsing by Andrew Rissing
Here is another way of doing it
public DataSet CreateTable(string source)
{
using (var connection = new OleDbConnection(GetConnectionString(source, true)))
{
var dataSet = new DataSet();
connection.Open();
var schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable == null)
return dataSet;
var sheetName = "";
foreach (DataRow row in schemaTable.Rows)
{
sheetName = row["TABLE_NAME"].ToString();
break;
}
var command = string.Format("SELECT * FROM [{0}$]", sheetName);
var adapter = new OleDbDataAdapter(command, connection);
adapter.TableMappings.Add("TABLE", "TestTable");
adapter.Fill(dataSet);
connection.Close();
return dataSet;
}
}
//
private string GetConnectionString(string source, bool hasHeader)
{
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", source, (hasHeader ? "YES" : "NO"));
}

How to Display Tab Delimited Text File Into DataGridView including the Headers?

I have this MS Access table with the following structure:
I extracted the data into a tab delimited text file with no text qualifier:
I found this article but it doesn't work for tab delimited file.
I don't know how to display this data into DataGridView including the headers. Can you please help me?
Thanks in advance.
DataGridView1.DataSource = CsvFileToDatatable(#"c:\a.csv",true);
public DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not
{
string header = "No";
string sql = string.Empty;
DataTable dataTable = null;
string pathOnly = string.Empty;
string fileName = string.Empty;
try
{
pathOnly = Path.GetDirectoryName(path);
fileName = Path.GetFileName(path);
sql = #"SELECT * FROM [" + fileName + "]";
if (IsFirstRowHeader)
{
header = "Yes";
}
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
}
}
}
}
finally
{
}
return dataTable;
}

Categories

Resources