I need this code C# working for files excel 2003 and 2007 version.
I can't get this C# code working to convert excel file (xls) on csv file.
If try with excel file extension xlsx it's all ok but if try with extension xls I have error in this line:
result.Tables[0].TableName.ToString();
My code below, what's wrong?
code-behind
FileUploadControl.SaveAs(Server.MapPath("/public/") + filename);
System.IO.FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + ",";
}
row_no++;
csvData += "\n";
}
keys = GetUniqueKey(8).ToUpper();
output = System.Web.HttpContext.Current.Server.MapPath("/public/target_" + keys.ToString() + ".csv");
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(csvData);
csv.Close();
Excel can be of two types:
Binary - Excel 2003 and older - xls
Zip - based on Open Office XML standards - Excel 2007 onwards - xlsx
You should try to use following for older excel format files:
ExcelReaderFactory.CreateBinaryReader(stream);
Use any Xls to Xslx conversation tool. You can try Aspose libraries. I think it's licensed but you can try trail version.
You can do all other conversions as well using these libraries.
Here's how I do it - OLEDB - get the first sheet name, and remove all empty rows. Replace //whatever you need to do with your logic.
//Your Method signature
{
//create connection string
var connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path +
";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
//process
using (var conn = new OleDbConnection(connStr))
{
conn.Open();
//programatically get the first sheet, whatever it is named.
var sheetName = GetSheetNames(conn)[0].SheetNameOf;
var adapter = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", sheetName), connStr);
var ds = new DataSet();
adapter.Fill(ds, "anyNameHere");
var data = ds.Tables["anyNameHere"];
//copy and remove blank lines
var resData = data.Clone();
var filteredData = data.Rows.Cast<DataRow>().Where(
row => !row.ItemArray.All(
field => field is DBNull ||
field == null ||
(String.IsNullOrEmpty(field.ToString().Trim())))
);
filteredData.CopyToDataTable(resData, LoadOption.OverwriteChanges);
var newData = resData.AsEnumerable();
//whatever you need to do
}
public List<SheetName> GetSheetNames(OleDbConnection conn)
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
DataTable excelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheetNames = (from DataRow row in excelSchema.Rows
where !row["TABLE_NAME"].ToString().Contains("FilterDatabase")
select new SheetName { SheetNameOf = row["TABLE_NAME"].ToString() }
).ToList();
conn.Close();
return sheetNames;
}
You can use Aspose.Cells to convert excel file like xls or xlsx into csv format with the following simple code.
string filePath = #"F:\Downloads\source.xlsx";
Workbook workbook = new Workbook(filePath);
workbook.Save("output.csv", SaveFormat.CSV);
Note: I am working as developer evangelist at Aspose.
Related
I am Using the this code below in
private void Form1_Load(object sender, EventArgs e)
{
System.Data.DataTable dt;
SqlConnection con=new SqlConnection("Data Source=sanjay;Initial Catalog=Login;Integrated Security=True");
SqlCommand cmd=new SqlCommand("select * from login",con);
SqlDataAdapter sda=new SqlDataAdapter(cmd);
dt=new System.Data.DataTable();
sda.Fill(dt);
int srno = 1;
StringBuilder stb = new StringBuilder();
ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook();
String Todaysdate1 = DateTime.Now.ToString("dd-MM-yyyy");
string appPath = Path.Combine(Environment.CurrentDirectory + "\\");
if (!Directory.Exists(appPath + "\\" + Todaysdate1 + "\\TD"))
{
Directory.CreateDirectory(appPath + "\\" + Todaysdate1);
}
if (dt.Rows.Count > 0)
{
stb.Append("<html>");
stb.Append("<head>");
stb.Append("</head>");
stb.Append("<body>");
stb.Append("Sanju");
stb.Append("<table border=2>");
stb.Append("<tbody>");
stb.Append("<tr style='height:25px'>");
stb.Append("<td colspan='18' style='text-align:center;font-size:18px;font-weight:bold;min-width:50px'>");
stb.Append("<center> Form III - DEAF Voucher Preparation</center>");
stb.Append("</td>");
stb.Append("</tr>");
stb.Append("<tr style='height:21px'>");
stb.Append("<td colspan='18' style='text-align:center;font-size:16px;font-weight:bold;min-width:50px'>");
stb.Append("<center>2018-05-01</center>");
stb.Append("</td>");
stb.Append("</tr>");
stb.Append("<tr style='height:100px;font-weight:bold'>");
stb.Append("<td style='text-align:center;font-size:14px'>No.</td>");
stb.Append("</tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
stb.Append("<tr>");
stb.Append("<td>" + srno++ + " </td>");
stb.Append("<td nowrap>" + dt.Rows[i][0].ToString() + "</td>");
stb.Append("<td style='background-color:#ff99cc'></td>");
stb.Append("<td style='background-color:#ff99cc'></td>");
stb.Append("<td style='background-color:#ff99cc'></td>");
stb.Append("</tr>");
wb.Worksheets.Add(srno.ToString(), i);//Add worksheet
}
stb.Append("</tbody>");
stb.Append("</table>");
stb.Append("</body>");
stb.Append("</html>");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(appPath + "\\" + Todaysdate1 + "\\TD_Results_From.XLS"))
{
file.WriteLine(stb.ToString());
}
System.Diagnostics.Process.Start(appPath + "\\" + Todaysdate1 + "\\TD_Results_From.XLS");
}
I am used the Wb.SavaAs() only show the add worksheet but first worksheet not open I will access workbook and all worksheet each recede create the worksheet.
Add Multiple worksheet I am Using wb.Worksheets.Add(srno.ToString(), i); this statement
I am also using the closedXml
The problem is a only create the main worksheet but never open the all worksheet
Any Body Help Me
Advance Thank You
ClosedXML can not import HTML.
Can closedXML write out an HTML table for Excel
You have to parse the HTML yourself (using something like HTML Agility Pack) and put the content of each cell in the HTML table in the corresponding cell of the ClosedXML spreadsheet
You should do it like this:
public void WriteDataToExcel(DataTable dt, string fileName)
{
using (XLWorkbook wb = new XLWorkbook())
{
//Add DataTable in worksheet
wb.Worksheets.Add(dt);
using (Stream stream = new FileStream(fileName, FileMode.Create))
{
wb.SaveAs(stream);
}
}
}
Also, you could use Open XML like this sample project to export XLS:
Creating basic Excel workbook with Open XML
I have exported the data from database using HttpContext with formatting of table, tr and td. I want to read the same file and convert into datatable.
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='HTML Import;HDR={1};IMEX=1'" />
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1};IMEX=1'" />
private DataTable GetTableFromExcel()
{
DataTable dt = new DataTable();
try
{
if (exclFileUpload.HasFile)
{
string FileName = Path.GetFileName(exclFileUpload.PostedFile.FileName);
string Extension = Path.GetExtension(exclFileUpload.PostedFile.FileName);
string FolderPath = Server.MapPath(ConfigurationManager.AppSettings["FolderPath"]);
//string NewFileName = string.Format("{0}_{1}", DateTime.Now.ToString().Replace("/", "").Replace(" ", "").Replace(":", ""), FileName);
string FilePath = Path.Combine(string.Format("{0}/{1}", FolderPath, FileName));
exclFileUpload.SaveAs(FilePath);
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, true);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
File.Delete(FilePath);
}
}
catch (Exception ex)
{
}
return dt;
}
When using the second connection string I am getting error "External table is not in the expected format on connection.Open()." But when using the first, I am getting error on reading the sheet name.
Please tell me how to read the sheet or, directly, data from Excel.
I think This Third party dll-(ExcellDataReader) may help solve your problem.
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
I found this online:
C# Excel file OLEDB read HTML IMPORT
Here they say:
Instead of using the sheetname, you must use the page title in the
select statement without the $. SELECT * FROM [HTMLPageTitle]
In that post they also link to this manual, which may come in handy, but is too long to copy here:
http://ewbi.blogs.com/develops/2006/12/reading_html_ta.html
If that doesn't work, I t think you will have to recreate the original excel so it remains an excel file, and not HTML (if that is at all possible in your scenario)
You may be facing this issue due to different reasons. There are different solutions for this one of them is to make your solution debug as x86. Here is how you can change it to x86.
Right click on sloution from Visual studio.
Click configuration Manager
Select x86 from Active solution platform if available
If not available click New and select or type x86 and click ok.
Rebuild solution and run you application.
If this deos not solve your problem you may have to install 32 bit version of office system drivers. Here is a complete article explaining the problem.
After a deep research I found the solution.
First convert the particular Excel file to an html page by using the following code.
File.Move(Server.MapPath("~/Foldername/ExcelName.xls",Path.ChangeExtension(Server.MapPath("~/Foldername/ExcelName.xls"), ".html"));
we have to download HTML string and extract content. tag contains and tags but it may have style properties. So first we have to avoid these style properties and after we can get required content from table.
string url = Server.MapPath("~/FolderName/Excelname.html");
WebClient wc = new WebClient();
string fileContent = wc.DownloadString(url);
Here we have to format HTML tags for avoid style properties.
const string msgFormat = "table[{0}], tr[{1}], td[{2}], a: {3}, b: {4}";
const string table_pattern = "<table.*?>(.*?)</table>";
const string tr_pattern = "<tr.*?>(.*?)</tr>";
const string td_pattern = "<td.*?>(.*?)</td>";
const string a_pattern = "";
const string b_pattern = "<b>(.*?)</b>";
After through looping we can find <tr> and <td> elements. Then we can get content within <td></td> tags by using this method.
private static List<string> GetContents(string input, string pattern)
{
MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Singleline);
List<string> contents = new List<string>();
foreach (Match match in matches)
contents.Add(match.Value);
return contents;
}
Then we can insert imported records to database by each row.
Reference link here
Here's my situation. I'm designing a program that takes Excel files (which may be in csv, xls, or xlsx format) from a remote network drive, processes the data, then outputs and stores the results of that process. The program provides a listbox of filenames that are obtained from the remote network drive folder using the method detailed in the accepted answer here. Once the user selects a filename from the listbox, I want the program to find the file and obtain the information from it to do the data processing. I have tried using this method to read the data from the Excel file while in a threaded security context, but that method just fails without giving any kind of error. It seems to not terminate. Am I going about this the wrong way?
Edit - (Final Notes: I have taken out the OleDbDataAdapter and replaced it with EPPlus handling.)
I was able to scrub sensitive data from the code, so here it is:
protected void GetFile(object principalObj)
{
if (principalObj == null)
{
throw new ArgumentNullException("principalObj");
}
IPrincipal principal = (IPrincipal)principalObj;
Thread.CurrentPrincipal = principal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
WindowsImpersonationContext impersonationContext = null;
if (identity != null)
{
impersonationContext = identity.Impersonate();
}
try
{
string fileName = string.Format("{0}\\" + Files.SelectedValue, #"RemoteDirectoryHere");
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.14.0; data source={0}; Extended Properties=Excel 14.0;", fileName);
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Sheet1", connectionString);
DataSet ds = new DataSet();
adapter.Fill(ds, "Sheet1");
dataTable = ds.Tables["Sheet1"];
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
}
Additional Edit
Now xlsx files have been added to the mix.
Third Party
Third party solutions are not acceptable in this case (unless they allow unrestricted commercial use).
Attempts - (Final Notes: Ultimately I had to abandon OleDb connections.)
I have tried all of the different connection strings offered, and I have tried them with just one file type at a time. None of the connection strings worked with any of the file types.
Permissions
The User does have access to the file and its directory.
Your connection string might be the issue here. As far as I know, there isn't 1 that can read all xls, csv, and xlsx. I think you're using the XLSX connection string.
When I read xls, i use the following connection string:
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Having said that, I recommend using a 3rd party file reader/parser to read XLS and CSV since, from my experience, OleDbDataAdapter is wonky depending on the types of data that's being read (and how mixed they are within each column).
For XLS, try NPOI https://code.google.com/p/npoi/
For CSV, try http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
For XLSX, try EPPlus http://epplus.codeplex.com/
I've had great success with the above libraries.
Is it really important that you use an OleDb interface for this? I've always done it with Microsoft.Office.Excel.Interop, to wit:
using System;
using Microsoft.Office.Interop.Excel;
namespace StackOverflowExample
{
class Program
{
static void Main(string[] args)
{
var app = new Application();
var wkbk = app.Workbooks.Open(#"c:\data\foo.xls") as Workbook;
var wksht = wkbk.Sheets[1] as Worksheet; // not zero-based!
for (int row = 1; row <= 100; row++) // not zero-based!
{
Console.WriteLine("This is row #" + row.ToString());
for (int col = 1; col <= 100; col++)
{
Console.WriteLine("This is col #" + col.ToString());
var cell = wksht.Cells[row][col] as Range;
if (cell != null)
{
object val = cell.Value;
if (val != null)
{
Console.WriteLine("The value of the cell is " + val.ToString());
}
}
}
}
}
}
}
As you will be dealing with xlsx extension, you should rather opt for the new connection string.
public static string getConnectionString(string fileName, bool HDRValue, bool WriteExcel)
{
string hdrValue = HDRValue ? "YES" : "NO";
string writeExcel = WriteExcel ? string.Empty : "IMEX=1";
return "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + "Extended Properties=\"Excel 12.0 xml;HDR=" + hdrValue + ";" + writeExcel + "\"";
}
Above is the code for getting the connection string. First argument expects the actual path for file location. Second argument will decide whether to consider first row values as column headers or not. Third argument helps decide whether you want to open the connection to create and write the data or simply read the data. To read the data set it to "FALSE"
public static ReadData(string filePath, string sheetName, List<string> fieldsToRead, int startPoint, int endPoint)
{
DataTable dt = new DataTable();
try
{
string ConnectionString = ProcessFile.getConnectionString(filePath, false, false);
using (OleDbConnection cn = new OleDbConnection(ConnectionString))
{
cn.Open();
DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
StringBuilder sb = new StringBuilder();
sb.Append("SELECT *");
sb.Append(" FROM [" + sheetName + fieldsToRead[0].ToUpper() + startPoint + ":" + fieldsToRead[1].ToUpper() + endPoint + "] ");
OleDbDataAdapter da = new OleDbDataAdapter(sb.ToString(), cn);
dt = new DataTable(sheetName);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string i = row[0].ToString();
}
}
cn.Dispose();
return fileDatas;
}
}
catch (Exception)
{
}
}
This is for reading 2007 Excel into dataset
DataSet ds = new DataSet();
try
{
string myConnStr = "";
myConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MyDataSource;Extended Properties=\"Excel 12.0;HDR=YES\"";
OleDbConnection myConn = new OleDbConnection(myConnStr);
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$] ", myConn);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
myConn.Open();
adapter.Fill(ds);
myConn.Close();
}
catch
{ }
return ds;
I am using IExcelDataReader to reader to read a excel sheet using following code:
private static IExcelDataReader FetchDataReaderForExcel(HttpPostedFile file)
{
IExcelDataReader dataReader = null;
if (null != file)
{
string fileExtension = Path.GetExtension(file.FileName);
switch (fileExtension)
{
case ".xls":
dataReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream);
break;
case ".xlsx":
dataReader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
break;
default:
dataReader = null;
break;
}
}
return dataReader;
}
When i am reading the excel sheet using this method sometime i am not able to read the data correctly. Sometime it is not able to read column other time it is not able to read the entire data. I need to format each column to normal text and then upload again, it works then. Excel contains data contains integer, string, datetime, hyperlink. Can anyone tell me what could be the problem or alternative for this?
I'm using oledb and it works perfect for me. Here is my example:
using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Filename + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\""))
{
//
string listName = "Sheet1";
con.Open();
try
{
DataSet ds = new DataSet();
OleDbDataAdapter odb = new OleDbDataAdapter("select * from [" + listName + "$]", con);
odb.Fill(ds);
con.Close();
foreach (DataRow myrow in ds.Tables[0].Rows)
{
Object[] cells = myrow.ItemArray;
if (cells[0].ToString().Length > 0 || cells[1].ToString().Length > 0 || cells[2].ToString().Length > 0)
{
/*
cells[0]
cells[1]
cells[2]
are getting values
*/
}
}
}
catch (Exception ex)
{
return null;
}
}
OLEDB.12.0 works with both .xls and .xlsx
If you are Uploading the file ,and the file has Many sheets in it and you want to read all the sheets you can follow this method....first write the Code for FileUPload and save the uploaded file in a path....using that path you can read the files
/// <summary>
/// This method retrieves the excel sheet names from
/// an excel workbook & reads the excel file
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns></returns>
#region GetsAllTheSheetNames of An Excel File
public static string[] ExcelSheetNames(String excelFile)
{
DataTable dt;
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=Yes'";
using (OleDbConnection objConn = new OleDbConnection(connString))
{
objConn.Open();
dt =
objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
string[] res = new string[dt.Rows.Count];
for (int i = 0; i < res.Length; i++)
{
string name = dt.Rows[i]["TABLE_NAME"].ToString();
if (name[0] == '\'')
{
//numeric sheetnames get single quotes around
//remove them here
if (Regex.IsMatch(name, #"^'\d\w+\$'$"))
{
name = name.Substring(1, name.Length - 2);
}
}
res[i] = name;
}
return res;
}
}
#endregion
//You can read files and store the data in a dataset use them
public static DataTable GetWorksheet(string excelFile,string worksheetName)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=Yes'";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connString);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter("select * from [" + worksheetName + "$]", con);
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
con.Close();
return excelDataSet.Tables[0];
}
Else U can use this method to read the excel file
Just Add the reference
click on the "AddReference" on solution explorer ,click on com tab and Add this reference
Microsoft.Office.Interop.Excel
And add this namespace in your code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Data;
static void Main(string[] args)
{
string Path = #"C:\samples\SEP DUMPS.xls";
// initialize the Excel Application class
Excel.Application app = new Excel.Application();
//Excel.Worksheet NwSheet;
Excel.Range ShtRange;
// create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(Path,0,true,5,"","",true,Excel.XlPlatform.xlWindows,"\t",false,false, 0,true,1,0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 1;
// that is which cell in the excel you are interesting to read.
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 5;
object colIndex3 = 4;
System.Text.StringBuilder sb = new StringBuilder();
try
{
while (((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
rowIndex =index;
string firstName = Convert.ToString( ((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2);
string lastName = Convert.ToString(((Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value2);
string Name = Convert.ToString(((Excel.Range)workSheet.Cells[rowIndex, colIndex3]).Value2);
string line = firstName + "," + lastName + "," + Name;
sb.Append(line); sb.Append(Environment.NewLine);
Console.WriteLine(" {0},{1},{2} ", firstName, lastName,Name);
index++;
}
Writetofile(sb.ToString());
ShtRange = workSheet.UsedRange;
Object[,] s = ShtRange.Value;
}
catch (Exception ex)
{
app.Quit();
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
Hope this helps you..........If u have any doubts Ask me...
I am trying to import a .csv file into my database. I am able to import an excel worksheet into my database, however due to different file format as .csv as from .xls, I need to make an import function specially for .csv.
Below is my code:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv")
{
Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>");
return;
}
// Generate the file name to save.
string strUploadFileName = #"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileUpload1.SaveAs(strUploadFileName);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr)){
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [columns] FROM +userrolelist", ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "DEMUserRoles";
bulkCopy.WriteToServer(dr);
Response.Write("<script>alert('DEM User Data imported');</script>");
}
}
}
}
else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>");
}
The file has been successfully saved, but the error says that the path for the file is not valid, even though the file has been successfully saved as .csv, therefore I am not able to continue with the process of importing the data into my database.
Below are the screenshots of my error:
In conclusion I am having the error that the file path which the csv file is saved is not valid, although the csv file is successfully saved. Need some help from experienced. Thank You
If you're reading a CSV file, your connection string should specify the directory containing your CSV file.
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
Path.GetDirectoryName(strUploadFileName);
You then use the filename in your SELECT statement:
"SELECT * FROM [" + Path.GetFileName(strUploadFileName) + "]"
I think you have this problem because you use "/" instead of "\"
Try to modify the path C:\.....
You need to use the backward slashes(\) on the file path.
string strUploadFileName = #"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
EDIT 1: I believe FileUpload1.SaveAs converts the / to \ internally to identify the correct location.
EDIT 2: Its the problem with your connectionstring, even though you are using .csv format, you need to set Excel 8.0 or Excel 12.0 Xml as the Extended Properties
Here is the sample:
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Excel 12.0 Xml;";
For other types, check the code of OLEDB section of my article.
To avoid the connection open you can use like
// Read the CSV file name & file path
// I am usisg here Kendo UI Uploader
string path = "";
string filenamee = "";
if (files != null)
{
foreach (var file in files)
{
var fileName = Path.GetFileName(file.FileName);
path = Path.GetFullPath(file.FileName);
filenamee = fileName;
}
// Read the CSV file data
StreamReader sr = new StreamReader(path);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
For more help you can also See This Link