Import image from Excel sheet into SQL Server table C# - c#

Here I want to insert all the data from my excel sheet into the SQL Server Table using C# code
I have the Excel sheet with data like this
ID Name Designation ProfilePicture
--------------------------------------------
1 ABC Manager C:\Pictures\1.jpg
2 DEF Asst.Manager C:\Pictures\2.jpg
And I have the Code to Insert the Datas into the Table
String filePath = filePathText.Text;
String fileExtension = "Excel 12.0";
if (filePath != null)
{
String xlsConnection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=" + "\"" + fileExtension + ";HDR=YES;\"";
String sqlConnection = "Your Connection String";
//Connection to Excel work book
OleDbConnection xlsConnectionString = new OleDbConnection(xlsConnection);
//Fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation],[ProfilePicture] from [Sheet1$]", xlsConnectionString);
xlsConnectionString.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnection);
//Destination table name
sqlBulk.DestinationTableName = "EXCEL_DATA";
sqlBulk.WriteToServer(dReader);
xlsConnectionString.Close();
}
This piece of code is run, if I click the button.
My Question is, How can I upload the picture from Excel Sheet (Sheet have the path of the image). to SQL Server Table. I want to get the picture by using the Imagepath provided in Excel Sheet and store it as varbinary(MAX) in SQL Server.

Thanks for the guys who really works to post the answer. Finally I got the solution to the problem myself.
Here is the code that helps to insert the images into the SQL Server by using the Path provided in Excel sheet.
private void insert_Click(object sender, EventArgs e)
{
UInt64 ID = 0;
String Name = String.Empty;
String Designation = String.Empty;
String ProfilePicture = String.Empty;
String filePath = filePathText.Text;
Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel._Worksheet xlWorksheet = null;
Excel.Range xlRange = null;
String sqlConnectionString = "Your Connection String goes here";
String insertRecord = "INSERT_USER_RECORDS";
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
SqlCommand sqlCommand = new SqlCommand(insertRecord, sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
if (filePath != null)
{
try
{
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open(filePath);
xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
MessageBox.Show((xlRange.Cells[row, col] as Microsoft.Office.Interop.Excel.Range).Value2.ToString());
// Check xlRange for Every run. And assign values to local variables. Here I just show the values using MsgBox
// If you get the Path of Image then call the function to Convert Image into byte
// Convert Image to Byte Function definition.
/* System.IO.FileStream fs = new System.IO.FileStream(ProfilePicture, System.IO.FileMode.Open);
Byte[] imageAsBytes = new Byte[fs.Length];
fs.Read(imageAsBytes, 0, imageAsBytes.Length);
fs.Close();
return imageAsBytes; */
}
sqlCommand.Parameters.Clear();
sqlCommand.Parameters.Add("#Name", SqlDbType.NVarChar).Value = FirstName;
sqlCommand.Parameters.Add("#Designation", SqlDbType.NVarChar).Value = LastName;
sqlCommand.Parameters.Add("#ProfilePicture", SqlDbType.VarBinary).Value = imageAsBytes;
sqlCommand.Parameters.Add("#ID", SqlDbType.BigInt).Value = ID;
sqlCommand.ExecuteNonQuery();
}
MessageBox.Show(Path.GetFileName(filePath) + "is Successfully imported to SQL Server", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
//Release All objects and close the Connection to prevent the Excel file from lock.
sqlConnection.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlRange);
Marshal.FinalReleaseComObject(xlWorksheet);
xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
}
}
else
{
MessageBox.Show("Please Select the Valid file to import");
}
}
This code works fine and helps me to insert the image into the SQL database from Excel.
No matter about the version of excel file.

Related

Get first sheet name within excel workbook

I'm trying to get the name of the first sheet of an excel workbook.
Instead of getting the sheets name in the order as it appears in the Excel workbook it appears sorted alphabetically.
Does anyone have an idea to get the names not sorted??
private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
// Connection String. Change the excel file to the file you
// will search.
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(connString);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
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++)
{
// Query each excel sheet.
}
return excelSheets;
}
catch(Exception ex)
{
return null;
}
finally
{
// Clean up.
if(objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if(dt != null)
{
dt.Dispose();
}
}
}
I already get a solution with my question.
//get sheet number 1 name
var excelFile = Path.GetFullPath(llFileName);
var excel = new Excel.Application();
var workbook = excel.Workbooks.Open(llFileName);
var sheet = (Excel.Worksheet)workbook.Worksheets.Item[1]; // 1 is the first item, this is NOT a zero-based collection
string sheetName = sheet.Name;
Hope it help for the other

Exporting datatable to a particular worksheet of an existing excel workbook

I have an excel workbook with two sheets. The second sheet contains two columns which provides data for dropdown list in sheet1. Now, I want to generate second sheet's data from database.
So, basically I want to insert data in an excel file in a particular sheet from database/gridview. Is there easier way to do that using itextSharp in asp.net.
You need to have installed Microsoft Visual Studio Tools for Office.
After that create common .NET project and add the reference to COM object Microsoft.Office.Interop.Excel.dll via 'Add Reference..' dialog.
Disclaimer: I wrote the code without checking it.
//open the workbook and set the worksheet
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(filePath);
Worksheeet ws = wb.sheets("WorkSheetName");
int i = 1; //used to track the column sin the excel sheet
//loop through datagrid
foreach (DataGridViewRow row in yourDataGrid)
{
//Cell[row, col]
ws.Cell[i, 1] = row.Cells[1] //assuming the location of item1
ws.Cell[i, 2] = row.Cells[2] //assuming the location of item2
i++;
}
//save and close
wb.Close(true);
This will dump the contents of a GridView into your Excel file.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn ;
string connectionString = null;
string sql = null;
connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM Product";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void button2_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
You can load a GridView from SQL Server in the following manner.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
SqlConnection connection;
SqlDataAdapter adapter;
SqlCommandBuilder cmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
string Sql;
Int32 i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
Sql = "select * from Product";
try
{
connection.Open();
adapter = new SqlDataAdapter(Sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
cmdBuilder = new SqlCommandBuilder(adapter);
changes = ds.GetChanges();
if (changes != null)
{
adapter.Update(changes);
}
MessageBox.Show("Changes Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Of course, you can push the data from SQL Server straight into Excel (or pull it into Excel from SQL Server).
Function ImportSQLtoRange
The function inserts SQL Server data to the target Excel range using ADO.
Function ImportSQLtoRange(ByVal conString As String, ByVal query As String, _
ByVal target As Range) As Integer
On Error Resume Next
' Object type and CreateObject function are used instead of ADODB.Connection,
' ADODB.Command for late binding without reference to
' Microsoft ActiveX Data Objects 2.x Library
' ADO API Reference
' http://msdn.microsoft.com/en-us/library/ms678086(v=VS.85).aspx
' Dim con As ADODB.Connection
Dim con As Object
Set con = CreateObject("ADODB.Connection")
con.ConnectionString = conString
' Dim cmd As ADODB.Command
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = query
cmd.CommandType = 1 ' adCmdText
' The Open method doesn't actually establish a connection to the server
' until a Recordset is opened on the Connection object
con.Open
cmd.ActiveConnection = con
' Dim rst As ADODB.Recordset
Dim rst As Object
Set rst = cmd.Execute
If rst Is Nothing Then
con.Close
Set con = Nothing
ImportSQLtoRange = 1
Exit Function
End If
Dim ws As Worksheet
Dim col As Integer
Set ws = target.Worksheet
' Column Names
For col = 0 To rst.Fields.Count - 1
ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name
Next
ws.Range(ws.Cells(target.row, target.Column), _
ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True
' Data from Recordset
ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst
rst.Close
con.Close
Set rst = Nothing
Set cmd = Nothing
Set con = Nothing
ImportSQLtoRange = 0
End Function
Code comments:
The query parameter can contain a SELECT or EXECUTE query.
The resulting data will be inserted starting from the top left cell of the target range.
Using Object types and the CreateObject function instead of direct use of ADO types
lets to avoid setting ActiveX Data Objects 2.x Library references on user computers.
This code works in Microsoft Excel 2003-2016.
Always use Set Nothing statements for ADODB.Connection and ADODB.Recordset objects to free resources.
See the link below for more ideas on how to do similar types of things.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#SQLServerDataImporttoExcelusingADO

C# removing unicode character

I'm attempting to insert text data from an Excel worksheet in to a MS SQL table using the C# sqlBulkCopy class. The problem I'm having is I get the notorious Received an invalid column length from the bcp client for colid 6 error. I later find out that the real problem is Excel Unicode formatting within the notes texts. if I just enter notes into the Excel cells the data insert works, otherwise it fails. Here is the code I'm attempting use in my C# script:
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(DBconn.ConnectionString);
{
sqlBulkCopy.DestinationTableName = "##MasterFileTemp";
foreach (DataColumn dc in MasterFileTemp.Columns)
{
for (int j = 1; j < MasterFileTemp.Rows.Count - 1; j++)
{
if (MasterFileTemp.Rows[0][dc].ToString() == "Notes")
{
int pos = dc.Ordinal;
string dataText = Regex.Replace(MasterFileTemp.Rows[j][pos].ToString(), #"[^\u0000-\u007F]", string.Empty);
MasterFileTemp.Rows[j][pos] = dataText;
MasterFileTemp.AcceptChanges();
MessageBox.Show(MasterFileTemp.Rows[j][pos].ToString());
}
}
}
sqlBulkCopy.WriteToServer(MasterFileTemp);
This is what the Excel text data looks like, notice the leading and trailing double quotes generated by Excel:
" -If additional information is needed, contact the partner requester on the Service Order Tab within the work space. For any other operational issues, email James
**Service requests include Portfolio Management (Watch list), Foreclosure, Pre-Foreclosure, Other Real Estate Owned (OREO), Asset Valuation only (no loan)
"
string strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;\";";
string GetExcelData = "Select * From [" + tabName + "A23:Z100]";
OleDbConnection cn = new OleDbConnection(strCn);
OleDbDataAdapter objAdapter2 = new OleDbDataAdapter(GetExcelData, cn);
DataSet ds2 = new DataSet();
objAdapter2.Fill(ds2, "dSheet1");
DataTable dt2 = ds2.Tables["dSheet1"];
Here the entired code:
namespace ST_426cda87cffe4ef6a10722ecf5f7fe65.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(Dts.Variables["User::MasterFileTemplate"].Value.ToString(),
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
String[] excelSheets = new String[excelBook.Worksheets.Count];
int z = 0;
foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)
{
excelSheets[z] = wSheet.Name;
z++;
}
excelBook.Close(false, Dts.Variables["User::MasterFileTemplate"].Value.ToString(), Missing.Value);
xlApp.Quit();
process_worksheets(excelSheets);
}
public void process_worksheets(string[] wsheets)
{
int r;
string[] vars = new string[1];
string field;
string filePath = (Dts.Variables["User::MasterFileTemplate"].Value.ToString());
string DataServer = (Dts.Variables["User::DataServer"].Value.ToString());
string strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;\";";
for (r=0; r < wsheets.Length; r++)
{
string tabName = wsheets[r].ToString() + "$";
string GetExcelDate = "Select * From [" + tabName + "A15:B16]"; //This is the Excel line number for Prod Completed date and Completed by
string GetExcelData = "Select * From [" + tabName + "A23:Z100]"; //This is the Excel line number where the header columns and data start
OleDbConnection cn = new OleDbConnection(strCn);
SqlConnection DBconn = new SqlConnection();
DBconn.ConnectionString = "Data Source="+DataServer + ";Initial Catalog=FNC;" + "Integrated Security=SSPI";
OleDbDataAdapter objAdapter = new OleDbDataAdapter(GetExcelDate, cn);
// This Dataset contains the header columns and data
DataSet ds = new DataSet();
objAdapter.Fill(ds, "dSheet1");
DataTable dt = ds.Tables["dSheet1"];
///**** Parse Excel Serial Date ***/
string dtt = (dt.Rows[0][1].ToString());
DateTime signoffDte = DateTime.Parse(dtt);
DateTime currentDte = System.DateTime.Today;
/// Check to see if Production sign-off date is less than current date and signed by is empty
if ((signoffDte > currentDte) || (dt.Rows[1][1].ToString() == ""))
{
// MessageBox.Show(tabName.ToString() + "Date requirment Failed..processing next");
continue; //Skip worksheet if Production signoff date or signature is invalid
}
else
{
//This Dataset contains the header columns and data
OleDbDataAdapter objAdapter2 = new OleDbDataAdapter(GetExcelData, cn);
DataSet ds2 = new DataSet();
objAdapter2.Fill(ds2, "dSheet1");
DataTable dt2 = ds2.Tables["dSheet1"];
DataTable dth = dt2.Clone();
dth.ImportRow(dt2.Rows[0]);
/*** Create Master File Temp Table from Excel Template source file ***/
CreateTempTableAndBulkCopyData(dt2,DBconn);
/*****************************************************************************/
/* Loop thru Excel Template File and only select the first row (Headers) */
/*****************************************************************************/
for (int i = 0; i < 1; i++) //Gets first row "A1:Z1" (column headers of excel spreadsheet)
{
// y=3 is static and must not be changed. This sets Partner_org_PK,Partner_ID,Partner_Name as key columns to perform SQL JOIN on
for (int y = 3; y < dth.Columns.Count; y++)
{
field = dth.Rows[0][y].ToString();
vars[0] = field;
UpdateMasterFileTable(DBconn, vars, dth); // Performs an update to the Partner Profile Table via a join on the Master File Temp table
}
UpdateValidation(DBconn, dth, tabName);
}
ds.Clear();
ds2.Clear();
dt.Clear();
dth.Clear();
cn.Close();
DBconn.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
MessageBox.Show("Processed......" + tabName.ToString());
System.Threading.Thread.Sleep(3000);
}
}
/**************************************************************************************************/
/* Creates Master File Global Temp Table ###MasterFileTemp and Bulk Copy Excel data into it */
/**************************************************************************************************/
public static void CreateTempTableAndBulkCopyData(DataTable dt2, SqlConnection DBconn)
{
DataTable MasterFileTemp = dt2;
string createTempTable = "CREATE TABLE ##MasterFileTemp(";
foreach (DataColumn dc in MasterFileTemp.Columns)
{
createTempTable += MasterFileTemp.Rows[0][dc] + " Varchar(255),";
}
createTempTable = createTempTable.Remove(createTempTable.Length - 1); //remove trailing, unecessary comma
createTempTable += ")"; // cap-off with ")" to complete the CREATE ##TEMP TABLE DDL
{
//Create temp table command
SqlCommand command = new SqlCommand(createTempTable, DBconn);
DBconn.Open();
command.ExecuteNonQuery();
MessageBox.Show(createTempTable.ToString());
//Copy the DataTable to SQL Server Table using SqlBulkCopy
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(DBconn.ConnectionString);
{
sqlBulkCopy.DestinationTableName = "##MasterFileTemp";
foreach (DataColumn dc in MasterFileTemp.Columns)
{
for (int j = 1; j < MasterFileTemp.Rows.Count - 1; j++)
{
if (MasterFileTemp.Rows[0][dc].ToString() == "Notes")
{
int pos = dc.Ordinal;
string dataText = MasterFileTemp.Rows[j][pos].ToString().Replace("\r\n", String.Empty);
MasterFileTemp.Rows[j][pos] = dataText;
MasterFileTemp.AcceptChanges();
//MessageBox.Show(MasterFileTemp.Rows[j][pos].ToString());
}
}
}
sqlBulkCopy.WriteToServer(MasterFileTemp);
}
}
}
/**************************************************************************************************/
/* Performs an up to the Partner Profile Table via a UPDATE join on the Master File Temp table */
/**************************************************************************************************/
public void UpdateMasterFileTable(SqlConnection DBconn, string[] vars, DataTable dth)
{
string[] upvariable = vars;
string sqlUpate = "UPDATE [dbo].[xstg_Partner_Profile]" +
" SET [dbo].[xstg_Partner_Profile]." + upvariable[0] + "=##MasterFileTemp." + upvariable[0] +
" FROM ##MasterFileTemp" +
" WHERE [dbo].[xstg_Partner_Profile].Partner_Id= ##MasterFileTemp." + dth.Rows[0][1].ToString() +
" AND [dbo].[xstg_Partner_Profile].Partner_Name= ##MasterFileTemp." + dth.Rows[0][2].ToString();
SqlCommand command = new SqlCommand(sqlUpate, DBconn);
command.ExecuteNonQuery();
MessageBox.Show(sqlUpate.ToString());
}
/**************************************************************************************************/
/* Performs the update validation against production 90100 UI Report and creates Excel mismatch */
/* output for each worksheet tab in masterfileupdate template
/**************************************************************************************************/
public void UpdateValidation(SqlConnection DBconn, DataTable dth, string tabName)
{
string SelectSQL;
string SelectFields=null;
for (int x = 3; x < dth.Columns.Count; x++)
{
SelectFields += " p2." +dth.Rows[0][x]+ ", ";
}
SelectFields = SelectFields.Remove(SelectFields.Length - 2); //remove trailing comma
SelectSQL = "SELECT p2.Partner_ID, p2.Partner_Name,";
SelectSQL += SelectFields;
string ValidationSQL = " FROM (select * from dbo.Partner_Profile_CMS_Settings) p1" +
" FULL OUTER JOIN (Select * from dbo.xstg_Partner_Profile) p2" +
" ON p1.Partner_ID = p2.Partner_ID and p1.Partner_Name=p2.Partner_Name" +
" WHERE";
SelectSQL += ValidationSQL; //Append select statement as one
string ValidationSQLWhere=null;
for (int y = 3; y < dth.Columns.Count; y++) //loop through data columns to get columns for update - mismatch. This is dynamic and makes up the Where clause
{
ValidationSQLWhere += " (P1."+dth.Rows[0][y]+" <> p2."+dth.Rows[0][y]+") OR";
}
ValidationSQLWhere = ValidationSQLWhere.Remove(ValidationSQLWhere.Length - 2); //Remove "OR" two characters from the select statement where clause
SelectSQL += ValidationSQLWhere; //Append Where clause string to main Select string
MessageBox.Show("Validating... " + tabName); //Display entire string
//Build SQL connection to run mismatch query, passing in SELECT statement above
SqlDataAdapter VSAdapter = new SqlDataAdapter(SelectSQL, DBconn);
// This Dataset contains Vaildate data
DataSet validateDs = new DataSet();
VSAdapter.Fill(validateDs, "VSheet1");
DataTable validationTemp = validateDs.Tables["VSheet1"];
String currentDate = DateTime.Now.ToString("MMddyyyy");
String outputStatus="Validation is 100% accurate";
/* Set up Excel workbook instance and loop through each worksheet avaialble file output */
/****************************************************************************************/
Excel.Application oXL = new Excel.ApplicationClass();
oXL.DisplayAlerts = false;
Excel.Workbooks oWBs = oXL.Workbooks;
Excel.Workbook oWB = null;
Excel.Worksheet oSheet;
tabName = tabName.Remove(tabName.Length-1); //remove training '$' from mismatch worksheets
/* If the mismatch output file does not exist, create mismatch file and write out first worksheet */
if (!File.Exists(Dts.Variables["User::MismatchOutputFile"].Value.ToString()))
{
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.Worksheets.get_Item(1);
oSheet.Name = tabName;
int rowCount = 0;
if (validationTemp.Rows.Count >= 1)
{
foreach (DataRow dr in validationTemp.Rows)
{
rowCount += 1;
for (int i = 1; i < validationTemp.Columns.Count + 1; i++)
{
// Add the header time first only
if (rowCount == 2)
{
oSheet.Cells[1, i] = validationTemp.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
}
else
{
// MessageBox.Show("Validation is 100% accurate");
oSheet.Cells[rowCount, 2] = outputStatus.ToString();
}
oWB.SaveAs(Dts.Variables["User::MismatchOutputFile"].Value.ToString(), Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlShared,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
}
else /* If mismatch file already exists, loop thru and append additional worksheets */
{
System.Threading.Thread.Sleep(1000);
try
{
oXL.DisplayAlerts = false;
Excel.Sheets xlSheets = null;
oWB = oXL.Workbooks.Open(Dts.Variables["User::MismatchOutputFile"].Value.ToString(),
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
xlSheets = (Excel.Sheets)oWB.Sheets;
oSheet = (Excel.Worksheet)xlSheets.Add(Type.Missing, xlSheets[1], Type.Missing, Type.Missing);
oSheet.Name = tabName;
int rowCount = 0;
if (validationTemp.Rows.Count > 1)
{
foreach (DataRow dr in validationTemp.Rows)
{
rowCount += 1;
for (int i = 1; i < validationTemp.Columns.Count + 1; i++)
{
// Add the header time first only
if (rowCount == 2)
{
oSheet.Cells[1, i] = validationTemp.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
}else
{
// MessageBox.Show("Validation is 100% accurate");
oSheet.Cells[rowCount, 2] = outputStatus.ToString();
}
oWB.SaveAs(Dts.Variables["User::MismatchOutputFile"].Value.ToString(), Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(true, Dts.Variables["User::MismatchOutputFile"].Value.ToString(), Type.Missing);
oWBs.Close();
oXL.Quit();
Marshal.ReleaseComObject(oXL);
}
finally
{
}
}
}
}
}
You are saying Excel, but your code is using a DataTable. Why wouldn't you directly SqlBulkCopy from the Excel itself?
Instead of using a global temp table, you could SqlBulkCopy to a local temp table, setting the text fields' datatype to NVarchar(max) and you shouldn't have a problem. SQL server supports unicode.
Edit: Ahha, I think now I see where you are going wrong. "Excel generated text data" you say. Is that a CSV file? Excel doesn't know how to save a legal CSV in the first place. Don't save to a text file. If you do, then there isn't an 'importer' that could read that data back right. Instead directly SqlBulkCopy from Excel without using any other intermediate text file or datatable.
Issue resolved. I identified that the column sizes where too small to accomodate the sqlBlkCopy operation. Change the size from varchar(255) to varchar(2000)

How to convert datatype before Importing Excel file to Sql database

Here I have this Import from excel file to sql database class. It was working correctly till now but as my excel file cells are all strings type , So when Importing , the datatype does not match as sql database. How to convert it to their respective datatype before importing?
public static void ImportToSql(string excelfilepath)
{
string myexceldataquery = "select LocalSKU,ItemName, QOH,Price,Discontinued,Barcode,Integer2,Integer3,SalePrice,SaleOn,Price2 from [sheet1$]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + excelfilepath + "; Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=2\"";
string ssqlconnectionstring = "Data Source=DELL\\SQLSERVER1;Trusted_Connection=True;DATABASE=Test;CONNECTION RESET=FALSE";
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlCommand sqlcmd = new SqlCommand(#"MERGE Inventory AS target
USING (select LocalSKU,ItemName, QOH,Price,Discontinued,Barcode,Integer2,Integer3,SalePrice,SaleOn,Price2 from #source) as source
ON (source.LocalSKU = target.LocalSKU)
WHEN MATCHED THEN
UPDATE SET ItemName=source.ItemName,Price=source.Price,Discontinued=source.Discontinued,Barcode=source.Barcode,Integer2=source.Integer2,Integer3 = source.QOH,SalePrice=source.SalePrice,SaleOn=source.SaleOn,Price2=source.Price2;", sqlconn);
SqlParameter param;
param = sqlcmd.Parameters.AddWithValue("#source",dr);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.InventoryType";
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
while (dr.Read())
{
}
oledbconn.Close();
Console.WriteLine(".xlsx file imported succssessfully into database.");
}
The easiest thing to do would be to convert them in your SQL statement by using CAST:
SqlCommand sqlcmd = new SqlCommand(
#"MERGE Inventory AS target
USING (select LocalSKU, ItemName, QOH = CAST(QOH AS int)
, Price = CAST(Price AS decimal(10,2)), Discontinued = CAST(Discontinued AS bit)
, Barcode, Integer2 = CAST(Integer2 AS int)
, Integer3 = CAST(Integer3 AS int), SalePrice = CAST(SalePrice AS decimal(10,2))
, SaleOn, Price2 = CAST(Price2 AS decimal(10,2)) from #source) as source
ON (source.LocalSKU = target.LocalSKU)
WHEN MATCHED THEN
UPDATE (. . . )
I'm guessing on some of the conversions, but you get the idea. You'll need to make sure that the data in the spreadsheet all match the datatypes you want to convert them to, as one mistake will cause the whole statement to fail. Something more robust will take a lot more code.
First browse the excel file and put data in datagrid and then read datagrid row one by one.
i give you 2 function for that. one is browse the excel file and put data in datagrid and second one is read datagrid and put record in database
Excel Export Function
private void export_btn_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application ExcelApp =
new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook ExcelBook;
Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;
int i = 0;
int j = 0;
//create object of excel
ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
//export header
for (i = 1; i <= this.dataGridView1.Columns.Count; i++)
{
ExcelSheet.Cells[1, i] = this.dataGridView1.Columns[i - 1].HeaderText;
}
//export data
for (i = 1; i <= this.dataGridView1.RowCount; i++)
{
for (j = 1; j <= dataGridView1.Columns.Count; j++)
{
ExcelSheet.Cells[i + 1, j] = dataGridView1.Rows[i - 1].Cells[j - 1].Value;
}
}
ExcelApp.Visible = true;
//set font Khmer OS System to data range
Microsoft.Office.Interop.Excel.Range myRange = ExcelSheet.get_Range(
ExcelSheet.Cells[1, 1],
ExcelSheet.Cells[this.dataGridView1.RowCount + 1,
this.dataGridView1.Columns.Count]);
Microsoft.Office.Interop.Excel.Font x = myRange.Font;
x.Name = "Arial";
x.Size = 10;
//set bold font to column header
myRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, 1],
ExcelSheet.Cells[1, this.dataGridView1.Columns.Count]);
x = myRange.Font;
x.Bold = true;
//autofit all columns
myRange.EntireColumn.AutoFit();
ExcelApp.ActiveWorkbook.SaveCopyAs("E:\\reports.xlsx");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("Excel file created,you can find the file E:\\reports.xlsx");
//
ExcelSheet = null;
ExcelBook = null;
ExcelApp = null;
}
Read Datagrid
public void readDataGrid()
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
try
{
//Here read one by one cell and convert it into your required datatype and store it in
String rowcell1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
}
catch (Exception err)
{
}
count++;
}
}
I this is help you.

Unable to read excel sheet using ExcelReader in ASP.Net?

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...

Categories