csv reading using OLEDB command - c#

Am trying to read a csv file using oledb command. Following is am using.
This code execute smoothly. But i need to remove first row from csv file and set second row as column header of the datatable. Is it possible?
static DataTable ImportCsvFileToDataTable(string filename, string fullPath)
{
FileInfo file = new FileInfo(fullPath);
using (OleDbConnection con =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
file.DirectoryName + "\";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';"))
{
using (OleDbCommand cmd = new OleDbCommand(string.Format
("SELECT * FROM [{0}]", file.Name), con))
{
con.Open();
// Using a DataTable to process the data
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable tbl = new DataTable(filename);
adp.Fill(tbl);
return tbl;
}
}
}
}

I shed much blood trying to develop the perfect method to import CSV's into DataTable. Here's the result. It parses first row as column headers. This method works with Ace OleDB 12, but should with no problem work with Jet OleDB 4 as well.
public static DataTable FromCSV(string FilePath, char Delimiter = ',')
{
DataTable dt = new DataTable();
Dictionary<string, string> props = new Dictionary<string, string>();
if (!File.Exists(FilePath))
return null;
if (FilePath.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
{
props["Provider"] = "Microsoft.Ace.OLEDB.12.0";
props["Extended Properties"] = "\"Text;FMT=Delimited\"";
props["Data Source"] = Path.GetDirectoryName(FilePath);
}
else
return null;
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}
string connectionString = sb.ToString();
File.Delete(Path.GetDirectoryName(FilePath) + "/schema.ini");
using (StreamWriter sw = new StreamWriter(Path.GetDirectoryName(FilePath) + "/schema.ini", false))
{
sw.WriteLine("[" + Path.GetFileName(FilePath) + "]");
sw.WriteLine("Format=Delimited(" + Delimiter + ")");
sw.WriteLine("DecimalSymbol=.");
sw.WriteLine("ColNameHeader=True");
sw.WriteLine("MaxScanRows=1");
sw.Close();
sw.Dispose();
}
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM [" + Path.GetFileName(FilePath) + "] WHERE 1=0";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
using (StreamWriter sw = new StreamWriter(Path.GetDirectoryName(FilePath) + "/schema.ini", true))
{
for (int i = 0; i < dt.Columns.Count; i++)
{
string NewColumnName = dt.Columns[i].ColumnName.Replace(#"""", #"""""");
int ColumnNamePosition = NewColumnName.LastIndexOf("#csv.", StringComparison.OrdinalIgnoreCase);
if (ColumnNamePosition != -1)
NewColumnName = NewColumnName.Substring(ColumnNamePosition + "#csv.".Length);
if (NewColumnName.StartsWith("NoName"))
NewColumnName = "F" + (i + 1).ToString();
sw.WriteLine("col" + (i + 1).ToString() + "=" + NewColumnName + " Text");
}
sw.Close();
sw.Dispose();
}
dt.Columns.Clear();
cmd.CommandText = "SELECT * FROM [" + Path.GetFileName(FilePath) + "]";
da = new OleDbDataAdapter(cmd);
da.Fill(dt);
cmd = null;
conn.Close();
}
File.Delete(Path.GetDirectoryName(FilePath) + "/schema.ini");
return dt;
}

Perhaps something like this:
tbl.Rows[0].Delete();
DataRow r = tbl.Rows[0];
foreach(DataColumn c in tbl.Columns)
{
tbl.Columns[c.ColumnName].ColumnName = r[c.ColumnName].ToString();
}
tbl.Rows[0].Delete();

There is no built-in way to tell OLEDB to use the second row for the headers instead of the first row.
You will have to open the CSV file, remote the first row, and save it again. Fortunately, this is fairly easy to do:
var lines = File.ReadAllLines(oldFileName);
File.WriteAllLines(newFileName, lines.Skip(1));
(Add .ToArray() after Skip(1) if you are using a .NET version < 4.)

Related

OLEDB gives an error while trying to fetch data

When I tried to select all data from excel using OLEDB.I get an error of
Syntax error (missing operator) in query expression 'Created By'
Is this because of that space in the column name?
The query is:
SELECT Code,Name,Created By,Date FROM [Template$]
public DataTable GetExcelDataToTable(string filename, string dataExchangeSelectedColum)
{
//List<DataExchangeDefinition> dataExchange = new List<DataExchangeDefinition>();
string extension = Path.GetExtension(filename);
string connstring = string.Empty;
DataTable ExcelData = null;
try
{
switch (extension)
{
case ".xls":
connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString, filename);
break;
case ".xlsx":
connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString, filename);
break;
}
using (OleDbConnection connExcel = new OleDbConnection(connstring))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = connExcel;
connExcel.Open();
var dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
var firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmd.CommandText = "SELECT " + dataExchangeSelectedColum + " FROM [" + firstSheet + "]";
ExcelData = new DataTable();
OleDbDataAdapter oda = new OleDbDataAdapter();
oda.SelectCommand = cmd;
oda.Fill(ExcelData);
}
}
}
catch (Exception ex)
{
throw ex;
}
return ExcelData;
}
This is the code I tried, here dataExchangeSelectedColum contains the columns they are "Code, Name, Created By, Date"
You need to add square brackets around the column name if it contains spaces:
cmd.CommandText = $"SELECT [{dataExchangeSelectedColum}] FROM [{firstSheet}]";
EDIT after your comment:
If you want to select several columns which name may contain spaces:
public DataTable GetExcelDataToTable(string filename, IEnumerable<string> columns)
{
...
string formattedColumns = string.Join("," columns.Select(column => $"[{column}]"));
cmd.CommandText = $"SELECT {formattedColumns} FROM [{firstSheet}]";
...
}
which can be invoked the following way:
DataTable table = GetExcelDataToTable(fileName,
new string[] { "Code", "Name", "Created By", "Date" });
I have done it like this
List<string> selecttedColsList = dataExchangeSelectedColum.Split(',').ToList();
string formattedColumns = "";
//string comma = "";
for (int i = 0; i < selecttedColsList.Count; i++)
{
//formattedColumns = string.Join(",", selecttedColsList.Select(col => $"[" + selecttedColsList[i] + "]"));
formattedColumns+= ""+$"[" + selecttedColsList[i] + "]";
if (i != selecttedColsList.Count - 1)
{
formattedColumns += ",";
}
}

Updating cells using dataset read from xls file and save to CSV file

can somebody tell me why this update procedure doesn't work? I want to read data to dataset from XLS and it works just fine but UPDATE doesn't work at all. No errors, no changes, like it doesn't exist. The file creates but values are just a copy from original xls.
Xls sheet format is pretty simple, one column: id 1 2 3
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\name.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.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++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = " + tbox1.Text + " WHERE id = " + tbox2.Text + "", conn);
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString()); //for test's sake
string pathFile = #"path\filename.csv";
if (!File.Exists(pathFile))
{
File.Create(pathFile).Close();
}
File.AppendAllText(pathFile, str.ToString());
Something is wrong with parameters probably but I tried this way and also no go (I added 2nd column so id stays the same just to find proper row), I get UPDATE command syntax error on execute:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn= new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.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++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand("UPDATE " + xlsSheet + " SET nazwa = #nazwa WHERE id = #id", conn);
adapter.UpdateCommand.Parameters.AddWithValue("#id", tbox1.Text).OleDbType = OleDbType.Integer;
adapter.UpdateCommand.Parameters.AddWithValue("#nazwa", tbox2.Text).OleDbType = OleDbType.VarChar;
adapter.UpdateCommand.ExecuteNonQuery();
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString());
string sciezkaPlik = #"path\filename.csv";
if (!File.Exists(sciezkaPlik))
{
File.Create(sciezkaPlik).Close();
}
File.AppendAllText(sciezkaPlik, str.ToString());
I solved the issue. For future reference it works well like this:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.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++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
OleDbCommand odbc = new OleDbCommand("UPDATE ["+xlsSheet+"] SET nazwa = " + txtNewValue.Text + " WHERE id = " + txtID.Text + "", conn);
adapter.UpdateCommand = odbc;
odbc.Parameters.AddWithValue("nazwa", txtNewValue.Text).OleDbType = OleDbType.VarChar;
odbc.Parameters.AddWithValue("id", txtID.Text).OleDbType = OleDbType.Integer;
odbc.ExecuteNonQuery();
dataset.Clear();
adapter.Fill(dataset);
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray) /
{
str.Append(field.ToString());
str.Append(", ");
}
str = str.Replace(',', '\n');
}
string filePath= #"path\filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
File.WriteAllText(filePath, str.ToString());
EDIT - I think it may be that this line needs to have the parameters put in as a question mark instead of having the actual values passed in, so more like this:
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = ? WHERE id = ?", conn);
Then your next couple of lines are correct, they are clever enough to replace the question marks from the UpdateCommand with the actual values at run time:
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
Hare is a very simple method to do an insert into an Excel sheet.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to convert csv to datatable in c#, mvc

I'm converting .csv file to datatable like below.
string header = isFirstRowHeader ? "Yes" : "No";
string itinerarycsvfilePath = Path.GetDirectoryName(#"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
string filename = Path.GetFileName(#"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
string sql = #"SELECT * FROM [" + filename + "]";
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + itinerarycsvfilePath +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable("ItineraryDetails");
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
then the result when I look with quick watch
Am I doing something wrong.I feel like that because table does not show like columns.
what can I do for that.
hope your help.
See code below
public class CSVReader
{
public DataSet ReadCSVFile(string fullPath, bool headerRow)
{
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();
try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}

C# Add rows to Microsoft Access table

I want to import an Excel file to a Access table.
I have a code that works well the first time. It is making a loop through all the sheets of the excel file, and it inserts the records.
At the second time, I get an exception:
"The table already exists"
I know that the table already exists in the Access file! I want to insert more records on it! I don't want to drop it!
Anyone knows how to solve this?
Here it is the code:
class Program
{
static void Main(string[] args)
{
string ExcelFiles = System.Configuration.ConfigurationSettings.AppSettings["FilesLocation"];
string AccessFile = System.Configuration.ConfigurationSettings.AppSettings["AccessFileLocation"];
string[] files = Directory.GetFiles(ExcelFiles, "*.xlsx");
foreach (string excelFile in files)
{
string[] sheets = ListSheetInExcel(excelFile).ToArray();
foreach (string sheetName in sheets)
{
ImportSpreadsheet(
excelFile,
sheetName.Replace("'", ""),
"MyTable",
AccessFile);
}
}
}
public static void ImportSpreadsheet(string ExcelfileName, string ExcelsheetName, string AccesstableName, string AccessDatabase)
{
OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
String strExtendedProperties = String.Empty;
sbConnection.DataSource = ExcelfileName;
if (Path.GetExtension(ExcelfileName).Equals(".xls"))//for 97-03 Excel file
{
sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
}
else if (Path.GetExtension(ExcelfileName).Equals(".xlsx")) //for 2007 Excel file
{
sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
}
sbConnection.Add("Extended Properties", strExtendedProperties);
using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandText = #"SELECT * INTO [MS Access;Database="
+ AccessDatabase + "].["
+ AccesstableName + "] FROM ["
+ ExcelsheetName + "]";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.ExecuteNonQuery(); //THE ERROR OCCURS HERE !!!!!!!!
}
}
catch (DbException ex)
{
Console.WriteLine("Exception: {0}\r\n Stack Trace: {1}", ex.Message, ex.StackTrace);
}
finally
{
conn.Close();
}
}
}
public static List<string> ListSheetInExcel(string filePath)
{
OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
String strExtendedProperties = String.Empty;
sbConnection.DataSource = filePath;
if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
{
sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
}
else if (Path.GetExtension(filePath).Equals(".xlsx")) //for 2007 Excel file
{
sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
}
sbConnection.Add("Extended Properties", strExtendedProperties);
List<string> listSheet = new List<string>();
using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
{
conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
{
listSheet.Add(drSheet["TABLE_NAME"].ToString());
}
}
}
return listSheet;
}
}
I have found the solution.
The command "INSERT INTO" needs to create a new table.
The solution is to build a command without that need:
cmd.CommandText = #"INSERT INTO [MS Access;Database="
+ AccessDatabase + "].["
+ AccesstableName + "] SELECT * FROM ["
+ ExcelsheetName + "]";

how to read data column headers and data of each cell in Excel Using c#

I have an excel sheet similar to :
I want to read data columns header:All,col1,col2,col3,col4,col5
and get all cell data.for example cell in Row = 2 and column 2 = 0
I currently write this code :
OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT top 5 * FROM " + excelSheets[j], connString);
DataTable fooData = new DataTable();
dbAdapter.Fill(fooData);
foreach (DataRow row in fooData.Rows)
{
Response.Write(row[0].ToString());
//Response.Write(row[1].ToString());
}
but it return just a data table with 1 column and just row 1..5 text.
How I can do this?
Please say answer without using Linq to Excel Provider and Open Xml.
Edit 1:
string file_name = "C:\\Book1.xlsx";
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_name + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
Response.Write("Not Exist");
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
// Loop through all of the sheets if you want too...
for (int j = 0; j < excelSheets.Length; j++)
{
OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT top 100 * FROM " + excelSheets[j], connString);
DataTable fooData = new DataTable();
dbAdapter.Fill(fooData);
foreach (DataRow row in fooData.Rows)
{
Response.Write(row[0].ToString());
}
}
You get the column name for the first column for example by fooData.Columns[0].ColumnName - see http://msdn.microsoft.com/en-us/library/system.data.datacolumn.columnname.aspx
EDIT:
Change the SELECT to SELECT * FROM AND use Fill (0, 5, new DataTable[] { fooData }).
"SELECT * FROM [" + excelSheets[j] + "$A1:C5]"
Try this one. It should return all of the cells from A1 to C5.
The driver that you selected is for Excel 2007 ("Provider=Microsoft.ACE.OLEDB.12.0" in your connectionString). Is your Excel file 2007 or 2010?
For Only data column header for logic is here:
string filePath = "C:\\Book1.xlsx";
string connString = string.Empty;
if (path.EndsWith(".xlsx"))
{
//2007 Format
connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", path);
}
else
{
//2003 Format
connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", path);
}
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
//Read the First Sheet
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
con.Close();
string firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
//Read the Header Row
cmd.CommandText = "SELECT top 1 * From [" + firstSheet + "]";
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
DataTable HeaderColumns = new DataTable();
da.SelectCommand = cmd;
da.Fill(HeaderColumns);
List<string> Filedata = new List<string>();
foreach (DataColumn column in HeaderColumns.Columns)
{
string columnName = HeaderColumns.Rows[0][column.ColumnName].ToString();
Filedata.Add(columnName);
ViewBag.Data = Filedata;
}
}
}
}

Categories