Too many Connections in C# using MySQL while uploading CSV file - c#

I'd liked to know on how to resolve this kind of ERROR when I'm trying to insert a Data from CSV file into MYSQL database. Below is my Code:
while (null != (sLine = __reader.ReadLine()))
{
while (rexRunOnLine.IsMatch(sLine) && null != (sNextLine = __reader.ReadLine()))
{
sLine += "\n" + sNextLine;
__rowno++;
string[] values = rexCsvSplitter.Split(sLine);
billOfMaterials.Allotment_code = values[0];
billOfMaterials.category_name = values[1];
billOfMaterials.activity = values[2];
billOfMaterials.quantity = values[3];
billOfMaterials.end_unit_quantity = values[4];
billOfMaterials.unit = values[5];
billOfMaterials.description = values[6];
billOfMaterials.unit_cost = values[7];
billOfMaterials.regular_labor_cost = values[8];
billOfMaterials.end_unit_labor_cost = values[9];
billOfMaterials.type = values[10];
billOfMaterials.batch = int.Parse(values[11]);
billOfMaterials.AddBillOfMaterials();
yield return values;
}
__reader.Close();
}
Here is the ERROR that I encountered:
Too many Connections

Related

How can I get values from a csv file where some of the cells contain commas?

I have a script that imports a csv file and reads each line to update the corresponding item in Sitecore. It works for many of the products but the problem is for some products where certain cells in the row have commas in them (such as the product description).
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (UpdateFile.PostedFile != null)
{
var file = UpdateFile.PostedFile;
// check if valid csv file
message.InnerText = "Updating...";
Sitecore.Context.SetActiveSite("backedbybayer");
_database = Database.GetDatabase("master");
SitecoreContext context = new SitecoreContext(_database);
Item homeNode = context.GetHomeItem<Item>();
var productsItems =
homeNode.Axes.GetDescendants()
.Where(
child =>
child.TemplateID == new ID(TemplateFactory.FindTemplateId<IProductDetailPageItem>()));
try
{
using (StreamReader sr = new StreamReader(file.InputStream))
{
var firstLine = true;
string currentLine;
var productIdIndex = 0;
var industryIdIndex = 0;
var categoryIdIndex = 0;
var pestIdIndex = 0;
var titleIndex = 0;
string title;
string productId;
string categoryIds;
string industryIds;
while ((currentLine = sr.ReadLine()) != null)
{
var data = currentLine.Split(',').ToList();
if (firstLine)
{
// find index of the important columns
productIdIndex = data.IndexOf("ProductId");
industryIdIndex = data.IndexOf("PrimaryIndustryId");
categoryIdIndex = data.IndexOf("PrimaryCategoryId");
titleIndex = data.IndexOf("Title");
firstLine = false;
continue;
}
title = data[titleIndex];
productId = data[productIdIndex];
categoryIds = data[categoryIdIndex];
industryIds = data[industryIdIndex];
var products = productsItems.Where(x => x.DisplayName == title);
foreach (var product in products)
{
product.Editing.BeginEdit();
try
{
product.Fields["Product Id"].Value = productId;
product.Fields["Product Industry Ids"].Value = industryIds;
product.Fields["Category Ids"].Value = categoryIds;
}
finally
{
product.Editing.EndEdit();
}
}
}
}
// when done
message.InnerText = "Complete";
}
catch (Exception ex)
{
message.InnerText = "Error reading file";
}
}
}
The problem is that when a description field has commas, like "Product is an effective, preventative biofungicide," it gets split as well and throws off the index, so categoryIds = data[8] gets the wrong value.
The spreadsheet is data that is provided by our client, so I would rather not require the client to edit the file unless necessary. Is there a way I can handle this in my code? Is there a different way I can read the file that won't split everything by comma?
I suggest use Ado.Net, If the field's data are inside quotes and it will parse it like a field and ignore any commas inside this..
Code Example:
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
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 dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

Uploading a file to folder

With the code below I am able to save files to folder.
My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.
if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
int filesize = AnnualReport.PostedFile.ContentLength;
int filesizeP = ProjectReports.PostedFile.ContentLength;
int filesizePub = Publications.PostedFile.ContentLength;
int filesizeOther = Other.PostedFile.ContentLength;
int filesizeReg = RegistDoc.PostedFile.ContentLength;
if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
} else {
const string ReportDirectory = "REPORTS/";
//Other Document
string OtherPath = ReportDirectory + Other.FileName;
string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
int iterationOther = 1;
while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
iterationOther++;
}
//Registration Document
string RigisDocPath = ReportDirectory + RegistDoc.FileName;
string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
int iterationRE = 1;
while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
iterationRE++;
}
//Annual Reports
string ReportPath = ReportDirectory + AnnualReport.FileName;
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
iteration++;
}
//Project Report
string ProjecttPath = ReportDirectory + ProjectReports.FileName;
string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
int iterationP = 1;
while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
iterationP++;
}
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iterationPub = 1;
while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
iterationPub++;
}
ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
AnnualReport.SaveAs(Server.MapPath(ReportPath));
Publications.SaveAs(Server.MapPath(publicationPath));
RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
Other.SaveAs(Server.MapPath(OtherPath));
The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.
Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)
You can just check if the required documents are present. (looking at your exising code, present means document name object is not null)
If not, throw an error.
If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.
ie.
if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
I did beak down the code into diferent methods like #irreal suggested, like below;
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else
{
int filesizeP = Publications.PostedFile.ContentLength;
if (filesizeP > 2097152)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Publication is 2.0 MB');", true);
}
else
{
const string ReportDirectory = "REPORTS/";
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
{
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
iteration++;
}
Publications.SaveAs(Server.MapPath(publicationPath));
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
}
}
I then called it o the click event
try{
PublicationReporting();
}
catch (Exception ex)
{
pgError.Text = "Publication Exception Message: " + ex.Message;
}
finally
{
csoW_connection.Close();
}
From here it was pretty easy to figure out the problem.
I just needed to dispose the content in the upload field if no file was selected like this
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else{
//program continues}

Getting error: "There is no row at position zero"

I am trying to upload an txt file with and retreive data from the database for the data which is in the text file.I was working fine before but suddenly this error shows up.
This is what there in text file....
X341HRK20140331 1000002
W177WAK20140405 1000004
R969GOJ20140405 1000005
W214VLR20140405 1000006
When I load the text file it comes up with this error:
StreamReader reader = File.OpenText(ofd.FileName);
while ((line = reader.ReadLine()) != null && line.Trim().Length>0)
{
//MUST STRIP ANY LEADING BLANK SPACES
vrm = line.Substring(0, 7).Trim().Replace(" ","");
eventYear = line.Substring(7, 4);
eventMonth = line.Substring(11, 2);
eventDay = line.Substring(13, 2);
dateOfEvent = eventYear + "-" + eventMonth + "-" + eventDay;
enquirerReference = line.Substring(29, 6);
dateSettledString="";
vq_entry = "";
//lookup-up other data from ICPS
string stringCommand = "SELECT t_number, t_reference, t_zone_name, t_street_name, t_camera_ticket, t_date_finally_settled,te_event FROM tickets inner join ticket_events on tickets.t_number = ticket_events.te_system_ref WHERE t_number=#enquirerReference";
SqlCommand command = new SqlCommand(stringCommand, connection);
command.CommandTimeout = 900;
command.Parameters.AddWithValue("#enquirerReference", enquirerReference);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable tblTemp = new DataTable("DataSet");
adapter.Fill(tblTemp);
ticketRef = tblTemp.Rows[0]["t_reference"].ToString(); -- this is where I receive this error.
site_zoneName = tblTemp.Rows[0]["t_zone_name"].ToString();
site_streetName = tblTemp.Rows[0]["t_street_name"].ToString();
issue_type = tblTemp.Rows[0]["t_camera_ticket"].ToString();
issue_type = issue_type.Replace("-1", "Camera");
issue_type = issue_type.Replace("0", "Manual");
dateSettledString = tblTemp.Rows[0]["t_date_finally_settled"].ToString().Trim();
events = tblTemp.Rows[0]["te_event"].ToString();
excluded = "";
//Read Ticket Exclusion File and process
StreamReader readerTEF = File.OpenText(ticket_exclude_file);
while ((lineTEF = readerTEF.ReadLine()) != null)
{
if (lineTEF == ticketRef)
{
excluded=excluded + "Excluded on Ticket Reference";
}
}
//Read ZoneName Exclusion File and process
//Check on matching zonename and streetname
StreamReader readerZNE = File.OpenText(zonename_exclude_file);
while ((lineZNE = readerZNE.ReadLine()) != null)
{
testSite=lineZNE.Split('#');
if (testSite[0] == site_zoneName && testSite[1] == site_streetName)
{
excluded = excluded + "Excluded on Zone & Street name";
}
}
//VOID VRM
if (vrm.Trim().ToUpper() == "VOID")
{
excluded = excluded + "Excluded on VRM";
}
DateTime dtEvent = DateTime.Parse(dateOfEvent);
TimeSpan span = DateTime.Now - dtEvent;
days_past_event = span.Days;
if (dateSettledString.Length > 5)
{
excluded = excluded + "Ticket Has Already Been Settled";
}
Put a check, your sql statement might not bring the data always
if(tblTemp !=null)
{
if(tblTemp.Rows.Count>0)
{
mticketRef = tblTemp.Rows[0]["t_reference"].ToString();
}
}
Also recommend you to use DBNull.Value in this case
i.e.
mticketRef = tblTemp.Rows[0]["t_reference"]!=DBNull.Value? tblTemp.Rows[0]["t_reference"].ToString():"";

How to avoid duplicate data when doing SQL INSERT from CSV

How can i avoid duplicate data when inserting from CSV file into my SQL server 2008 ?
#region Put to SQL
string line = null;
bool IsFirst = true;
string SqlSyntax = "INSERT INTO ORDRE ";
string sqlkey = "";
string sqlvalSELECT = "";
using (StreamReader sr = File.OpenText(filePath + "\\" + downloadname))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(';');
if (!String.IsNullOrEmpty(sqlvalSELECT)) sqlvalSELECT += "\nUNION ALL ";
if (data.Length > 0)
{
string sqlval = "";
foreach (object item in data)
{
if (IsFirst)
{
if (!String.IsNullOrWhiteSpace(sqlkey)) sqlkey += ",";
sqlkey += item.ToString();
}
else
{
if (!String.IsNullOrEmpty(sqlval)) sqlval += ",";
sqlval += item.ToString();
}
}
if (!String.IsNullOrEmpty(sqlval)) sqlvalSELECT += "SELECT " + sqlval;
IsFirst = false;
}
}
}
string sqlTOTAL = SqlSyntax + "(" + sqlkey + ")" + sqlvalSELECT;
//lbl_Message.Text = sqlTOTAL;
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
SqlCommand comm_Ftp_Insert = new SqlCommand(sqlTOTAL, connectionWrapper.conn);
comm_Ftp_Insert.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
#endregion
i make the methode to collect the data that already imported into SQL Server 2008.
how can i compare this to the CSV file ?
/// <summary>
/// Get the existed data on SQL
/// </summary>
/// <returns>Return List of Pers_Ordre with key OrdreId and ClientID</returns>
public List<Pers_Ordre> Get_Existed()
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
List<Pers_Ordre> oListOdr = new List<Pers_Ordre>();
string sql_Syntax = Outils.LoadFileToString(HttpContext.Current.Server.MapPath("~/SQL/OrdreFTP_GetExist.sql"));
SqlCommand comm_Command = new SqlCommand(sql_Syntax, connectionWrapper.conn);
SqlDataReader readerOne = comm_Command.ExecuteReader();
while (readerOne.Read())
{
Pers_Ordre oPersOrdre = new Pers_Ordre();
oPersOrdre.OrdreId = Convert.ToInt32(readerOne["NO_ORDRE"]);
oPersOrdre.ClientID = readerOne["CODE_CLIENT"].ToString();
oListOdr.Add(oPersOrdre);
}
return oListOdr;
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
Thanks you in advance,
Stev
Why not just insert the data from the csv into a temporary table and filter what you insert into the destination table to remove duplicate lines. That way you can let the database do the work which will be quicker anyway.
This is the easiest sql for what you need
insert into Order
select * from Order_Temp
WHERE NOT EXISTS
(
SELECT X
FROM Order o
WHERE o.NO_ORDRE = Order_Temp.NO_ORDRE
AND o.CODE_CLIENT = Order_Temp.CODE_CLIENT
)
Hope it helps
You could add unique constraints to the columns in your DB you don't want to duplicate. Then wrap your code in a try {} catch {}

C# 2.0 Fastest way to parse Excel spreadsheet [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading Excel files from C#
What is the fastest way to read large sets of data from excel from Csharp. Example code would be great . .
In our desktop environment, I have reached the best mix between performance, flexibility and stability by using Excel via COM.
Access to Excel is always via the same thread.
I use late-binding (in VB.Net) to make my app version independent.
The rest of the application is developed in C#, only this part and some other small parts are in VB, because they are easier in VB.Net.
Dim workBook As Object = GetObject(fileName)
Dim workSheet As Object = workBook.WorkSheets.Item(WorkSheetNr)
Dim range As Object = workSheet.Cells.Item(1, 1)
Dim range2 As Object = range.CurrentRegion
Dim rrow As Integer = range2.Row ' For XL97, first convert to integer. XL97 will generate an error '
Dim rcolumn As Integer = range2.Column
Dim top As Object = workSheet.Cells.Item(rrow, rcolumn)
Dim bottom As Object = top.Offset(range2.Rows.Count - 1, range2.Columns.Count - 1)
range = workSheet.Range(top, bottom)
Dim values As Object(,)
values = range.Value
Here you have a 2-dimensional array containing the values from Excel. The last statement gets the data from Excel to .Net.
Since the limits on the size of a Excel sheet, these cannot get very large, so memory should not be a problem.
We have done some tests on performance, on multiple systems. It is optimized to create as few as possible (out-of-process) COM calls.
This way was the one that has given us the best performance, specially since the data is directly in an array, and access to this data is faster as going through a dataset.
Slow in this solution is starting Excel. But if you need to process multiple files, right after each other, the cost of starting Excel is made only once.
Also I would not use this solution in a server environment.
public class ExcelHeaderValues
{
public static string CUSIP = "CUSIP";
public static string ORIG = "ORIG";
public static string PRICE = "PRICE";
public static int COLUMNCOUNT = 3;
}
public class ExcelParser
{
private ArrayList collOutput = null;
string sSheetName = String.Empty;
string[] strValidColumn;
int validRowCnt = 0;
string sColumnPositions = String.Empty;
OleDbCommand ExcelCommand;
OleDbDataAdapter ExcelAdapter;
OleDbConnection ExcelConnection = null;
DataSet dsSheet = null;
string path = string.Empty;
string identifier = string.Empty;
public ExcelParser()
{
collOutput = new ArrayList();
}
public void Extract()
{
bool headermatch = false;
string strCusip = string.Empty, strOrig = string.Empty, strPrice = string.Empty, strData = string.Empty;
string strCusipPos = string.Empty, strPricePos = string.Empty, strOrigPos = string.Empty;
string strColumnHeader = String.Empty;
int reqColcount = 0;
string[] strTemp;
bool bTemp = false;
bool validRow = false;
DataTable schemaTable = GetSchemaTable();
validRowCnt = 0;
foreach (DataRow dr in schemaTable.Rows)
{
if (dsSheet != null)
{
dsSheet.Reset();
dsSheet = null;
}
strCusipPos = string.Empty;
strOrigPos = string.Empty;
strPricePos = string.Empty;
if (isValidSheet(dr))
{
sColumnPositions = string.Empty;
validRowCnt = 0;
foreach (DataRow dataRow in dsSheet.Tables[0].Rows)
{
sColumnPositions = string.Empty;
if (headermatch == false)
{
sColumnPositions = string.Empty;
foreach (DataColumn column in dsSheet.Tables[0].Columns)
{
strColumnHeader = dataRow[column.ColumnName].ToString().ToUpper().Trim();
strColumnHeader = strColumnHeader.ToUpper();
if (strColumnHeader == ExcelHeaderValues.ORIG.ToUpper() || strColumnHeader == ExcelHeaderValues.CUSIP.ToUpper() || strColumnHeader == ExcelHeaderValues.PRICE.ToUpper())
{
bTemp = true;
validRow = true;
reqColcount = ExcelHeaderValues.COLUMNCOUNT;
}
if (bTemp)
{
bTemp = false;
sColumnPositions += column.ColumnName + "^" + strColumnHeader + ";";
}
}
strValidColumn = sColumnPositions.Trim().Split(';');
if (validRow == true && reqColcount == strValidColumn.Length - 1)
{
headermatch = true;
break;
}
validRowCnt++;
}
}
if (headermatch == true)
{
try
{
if (dsSheet.Tables[0].Rows.Count > 0)
{
if (strValidColumn.Length > 0)
{
for (int i = 0; i < strValidColumn.Length - 1; i++)
{
if (strValidColumn[i].ToUpper().Contains("CUSIP"))
{
strTemp = strValidColumn[i].ToString().Split('^');
strCusipPos = strTemp[0].ToString();
strTemp = null;
}
if (strValidColumn[i].ToUpper().Contains("PRICE"))
{
strTemp = strValidColumn[i].ToString().Split('^');
strPricePos = strTemp[0].ToString();
strTemp = null;
}
if (strValidColumn[i].ToUpper().Contains("ORIG"))
{
strTemp = strValidColumn[i].ToString().Split('^');
strOrigPos = strTemp[0].ToString();
strTemp = null;
}
}
}
for (int iData = validRowCnt; iData < dsSheet.Tables[0].Rows.Count; iData++)
{
if (strCusipPos.Trim() != "")
strCusip = dsSheet.Tables[0].Rows[iData][strCusipPos].ToString().Trim();
if (strOrigPos.Trim() != "")
strOrig = dsSheet.Tables[0].Rows[iData][strOrigPos].ToString().Trim();
if (strPricePos.Trim() != "")
strPrice = dsSheet.Tables[0].Rows[iData][strPricePos].ToString().Trim().ToUpper();
strData = "";
if (strCusip.Length == 9 && strCusip != "" && strPrice != "" && strOrig != "" && !strPrice.ToUpper().Contains("SOLD"))
strData = strCusip + "|" + Convert.ToDouble(strOrig) * 1000000 + "|" + strPrice + "|||||";
if (strData != null && strData != "")
collOutput.Add(strData);
strCusip = string.Empty;
strOrig = string.Empty;
strPrice = string.Empty;
strData = string.Empty;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
headermatch = false;
sColumnPositions = string.Empty;
strColumnHeader = string.Empty;
}
}
}
private bool isValidSheet(DataRow dr)
{
bool isValidSheet = false;
sSheetName = dr[2].ToString().ToUpper();
if (!(sSheetName.Contains("$_")) && !(sSheetName.Contains("$'_")) && (!sSheetName.Contains("Print_Titles".ToUpper())) && (dr[3].ToString() == "TABLE" && ((!sSheetName.Contains("Print_Area".ToUpper())))) && !(sSheetName.ToUpper() == "DLOFFERLOOKUP"))
{
if (sSheetName.Trim().ToUpper() != "Disclaimer$".ToUpper() && sSheetName.Trim().ToUpper() != "Summary$".ToUpper() && sSheetName.Trim().ToUpper() != "FORMULAS$" )
{
string sQry = string.Empty;
sQry = "SELECT * FROM [" + sSheetName + "]";
ExcelCommand = new OleDbCommand(sQry, ExcelConnection);
dsSheet = new DataSet();
ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
isValidSheet = false;
try
{
ExcelAdapter.Fill(dsSheet, sSheetName);
isValidSheet = true;
}
catch (Exception ex)
{
isValidSheet = false;
throw new Exception(ex.Message.ToString());
}
finally
{
ExcelAdapter = null;
ExcelCommand = null;
}
}
}
return isValidSheet;
}
private DataTable GetSchemaTable()
{
DataTable dt = null;
string connectionString = String.Empty;
connectionString = GetConnectionString();
ExcelConnection = new OleDbConnection(connectionString);
try
{
ExcelConnection.Open();
dt = ExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
private string GetConnectionString()
{
string connStr = String.Empty;
try
{
if (path.ToLower().Contains(".xlsx"))
{
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='" + path + "';" + "Extended Properties='Excel 12.0;HDR=No;IMEX=1;'";
}
else if (path.ToLower().Contains(".xlsm"))
{
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='" + path + "';" + "Extended Properties='Excel 12.0 Macro;HDR=No;IMEX=1;'";
}
else if (path.ToLower().Contains(".xls"))
{
connStr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + path + "';Extended Properties='Excel 8.0;HDR=No;IMEX=1;'";
}
else
{connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='" + path + "';" + "Extended Properties='HTML Import;IMEX=1;HDR=No;'";
}
}
catch (Exception ex)
{
throw ex;
}
return connStr;
}
}

Categories

Resources