xxxxxx is not a valid path. Make sure that the path name is - windows

I have windows application that can access files from setting.ini file I modified it and get access to them from my code. but still getting this error like 'C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
here is my setting.ini file code :
[UserDetail]
UserID=xxxxxxx
PassWord=xxxxxxxx
[Connection]
contact=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
DebitISE=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE 1.xls
DebitLKP=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
[FilePath]
DebitISEClient=C:
[FileName]
DebitISEClient=Contact_06-07-2015.txt
and here my code for accessing this files from ini file :
private void button1_Click(object sender, EventArgs e)
{
string filepath = txtpayoutfile.Text;
string message = "";
string mobileno = "";
string name = "";
DataSet dsmaster = new DataSet();
string filepathc = ini.IniReadValue("Connection", "contact");
if (filepath == "")
{
MessageBox.Show("Import Contact File");
this.Show();
}
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepathc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepathc + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn1.Open(); ////exception occurs here
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbCommand cmdoledb = new OleDbCommand("Select * from [Sheet1$3:3000]", oledbConn);
OleDbDataAdapter daoledb = new OleDbDataAdapter(cmdoledb);
DataTable dt = new DataTable();
daoledb.Fill(dt);
}

Related

Output SQL Table to existing Excel file/ new worksheet in SSIS / C# in script task

Good day,
I had a request to create a SSIS package that would output an SQL table to an Excel file. I had no problem creating this. However, the client came back asking that they wanted to be able to output the SQL table content to an existing Excel file in a new worksheet. If the worksheet does not exists in my following script, it is being created. However, it just goes back in the loop and fail because now it exists.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
string currentTab;
DataTable ExcelFileTabs;
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
string FullExcelFilePath = FolderPath + ExcelFileName + ".xlsx";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FullExcelFilePath + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
// Verify if file exists
if (File.Exists(FullExcelFilePath))
{
//Verify if the sheet exists
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
currentTab = excelTable["TABLE_NAME"].ToString();
if (currentTab == SheetName)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine("The sheet " + SheetName + " that your are trying to create in " + FullExcelFilePath + " already exists.");
sw.WriteLine("Please enter another sheet name or delete the Excel file and try again.");
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Failure;
}
else
{
// Create the worksheet in the existing Excel file
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
}
}
else
{
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Can somebody please help me with this ? I am pretty new to C#, and English is not my primary language. Please let me know if this is not clear enough.
Thanks in advance for you time :-)
Mylene
You know when you are trying to find the solution way to fare when it is just in front of you ?
My code, before wanting to catch the error if the user was trying to add a worksheet that already exists, already was trowing an exception in those cases...
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
Error log :
System.Data.OleDb.OleDbException (0x80040E14): Table 'Test9' already exists.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ST_a21007570143466693913591932c30b7.ScriptMain.Main()
Problem resolved.

format export to excel using closedxml with Title

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

CKEditor file upload doesn't work properly with mvc 6

I'm trying to use the built in upload file of CKEditor, it works with my MVC5 project, but it doesn't work with my MVC6 project, the code for uploading the file is correct, I've tested it, and it actually upload the file to the server, but it doesn't populate the form with the URL and image information, here's the code for my MVC5 project that works:
public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.ContentLength > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + Path.GetFileName(upload.FileName);
var vFolderPath = Server.MapPath("/Upload/");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
upload.SaveAs(vFilePath);
vImagePath = Url.Content("/Upload/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch(Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And here is the code for MVC6 project that doesn't work:
public async Task<ActionResult> UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.Length > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"');
var vFolderPath = Path.Combine(_environment.WebRootPath, "Files", "ArticleUploads");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
await upload.SaveAsAsync(vFilePath);
vImagePath = Url.Content("/Files/ArticleUploads/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch (Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And in CKEditor config file I have:
config.filebrowserImageUploadUrl = '/Admin/Article/UploadImage';
I've inspected the variables, and they send the same value, also worth to note that I'm using the same version of CKEditor, so that can't be the problem, I'd appreciate any help on this.
If the file gets uploaded and you don't see the image gets populated, I guess there should be some problem with the way you return your content, since you are returning html, try to specify your content type, like so:
return Content(vOutput, "text/html");
If that didn't solve your problem, you need to provide more information, tell us what exactly you get from this action in JavaScript side.

how to add a folder in the apk

I wanna to know how to add a folder in the apk.don't give me a solution about using the compress software directly. The apk was recompiled by the 'apktool.jar'. I need some code to achieve this problem. Hope one can solve my question as soon as possible.Thank you~
public static int zipMetaInfFolderToApk(String apkName, String folderName) throws IOException {
if(!new File(apkName).exists()){
return ConstantValue.ISQUESTION;
}
String zipName = apkName.substring(0, apkName.lastIndexOf(".")) + "."
+ "zip";
String bak_zipName = apkName.substring(0, apkName.lastIndexOf("."))
+ "_bak." + "zip";
FileUtils.renameFile(apkName, zipName);
ZipFile war = new ZipFile(zipName);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(
bak_zipName));
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
String name = "";
if(folderName.equals("")){
name = "META-INF/" + folderName;
}else{
name = "META-INF/" + folderName + "/";
}
ZipEntry e = new ZipEntry(name);
try{
append.putNextEntry(e);
}catch(ZipException e1){
append.closeEntry();
war.close();
append.close();
FileUtils.renameFile(zipName,apkName);
FileUtils.deleteFolder(bak_zipName);
e1.printStackTrace();
return ConstantValue.ISQUESTION;
}
append.closeEntry();
war.close();
append.close();
FileUtils.deleteFolder(zipName);
FileUtils.renameFile(bak_zipName, apkName);
return ConstantValue.ISNORMAL;
}

ASP.NET DynamicData Import Datas from Excel

I am using ASP.NET DynamicData v4.5 to allow admin to insert/update the records in the database.
My requirement is, -- Allow admin to import records for table from EXCEL file.
Source for the table may be available in excel files also. so i want admin to import data from file.
Is there any way i can achieve this in DynamicData ?
Yes you can do it, I've done it many times.
There is no built-in feature in Dynamic Data doing this but that's not a problem since it's pretty easy to implement.
The fact that you use ASP.NET Dynamic Data (like I do) is not really important for this task. As you probably know, you can create a regular ASP.NET form within a Dynamic Data project. You can also use a folder named /DynamicData/CustomPages to customize a Dynamic Data page. I suggest creating a new regular ASP.NET form called ImportingTool.aspx where your users will be able to import spreadsheets into your database. Once imported, they can use other dynamic data pages to edit the data.
Here is what you will need :
1- You need the user to upload a file, you will need
asp:fileupload or ajaxToolkit:AjaxFileUpload
2- You need to open that file, it will look like :
public void Import(FileUpload fileUpload)
{
if (fileUpload.HasFile)
{
string FileName = Path.GetFileName(fileUpload.PostedFile.FileName);
string Extension = Path.GetExtension(fileUpload.PostedFile.FileName);
string FilePath = HttpRuntime.AppDomainAppPath + "/Uploaded/" + FileName;
fileUpload.SaveAs(FilePath);
Import(FilePath, Extension);
}
}
3- You will need to import that file in your database, it will look like :
public Boolean Import(string FilePath, string Extension)
{
if (String.IsNullOrEmpty(FilePath) || String.IsNullOrEmpty(Extension))
{
return false;
}
string conStr;
string conStrNoHDR;
GetConnectionString(FilePath, Extension, out conStr, out conStrNoHDR);
OleDbConnection connection = new OleDbConnection(conStr);
OleDbConnection connectionNoHDR = new OleDbConnection(conStrNoHDR);
// depending on file extension, you might want to use connectionNoHDR
Import(connection);
connection.Close();
connectionNoHDR.Close();
}
private static void GetConnectionString(string FilePath, string Extension, out string conStr, out string conStrNoHDR)
{
conStr = "";
conStrNoHDR = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=YES\"";
conStrNoHDR = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=NO\"";
break;
case ".xlsx": //Excel 07
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 12.0 ";
conStrNoHDR = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0;HDR=NO\"";
break;
case ".csv":
conStr = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Path.GetDirectoryName(FilePath) + ";Extended Properties=\"Text;FMT=Delimited;HDR=NO\"";
break;
}
}
public static void Import(OleDbConnection connection)
{
String query = "SELECT * From [Report-LANG_VOCALLS$]";
DataTable dt = ImportUtils.GetData(connection, query);
string table = "Dialer";
string conn = ConfigurationManager.ConnectionStrings["Telecom"].ConnectionString;
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);
bulkCopy.ColumnMappings.Add("Phone", "Phone");
bulkCopy.ColumnMappings.Add("portfolio", "Portfolio_eng");
bulkCopy.ColumnMappings.Add("dept", "Department_eng");
ImportUtils.BulkCopy(dt, table, bulkCopy);
}
public static DataTable GetData(OleDbConnection connection, String query)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.CommandText = query;
cmdExcel.Connection = connection;
connection.Open();
adapter.SelectCommand = cmdExcel;
adapter.Fill(dt);
Debug.WriteLine(dt.Rows.Count);
connection.Close();
return dt;
}

Resources