Load data into multiple excel sheets depending on conditions dynamically - excel

I have a situation please help me out. I have to create multiple sheet in one excel file with different queries. Like i have to check if the particular column is null then the record against this query should be in excel file in new sheet and i have to check another column with other name if it is null or empty and then create a sheet for it and sheet should be created only if the query returns some result otherwise there should not be any empty sheet. i have 8 different columns to check .
For Example I have to execute following query which will be in source
SELECT DISTINCT AgencySourceSystemCode,SourceAgencyID,ProgramCode,PolicyNumber,EffectiveDate,AgencyName
FROM POL.vw_PolicyPremiumData
WHERE AgencyName IS NULL OR AgencyName = ''
And Sample result is
AgencySourceSystemCode SourceAgencyID
ProgramCode PolicyNumber
EffectiveDate AgencyName
GEN 1050- CAB DN17000008
2010-06-10 NULL
GEN 1050- CAB DN17000008
2011-06-10 NULL
GEN 1050- CAB DN17000008
2012-06-10 NULL
GEN 1050- CAB DN17000010
2010-06-10 NULL
GEN 1050- CAB DN17000010
2012-06-10 NULL
GEN 1050- CAB DN17000012
2010-06-22 NULL
GEN 1050- CAB DN17000012
2011-06-22 NULL
Here Agency Name is NULL like this i will have source query where Effective can be null .

I used this code snippet to create dynamic Excel file sheets .
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace ST_db9b6187d17c4dc99314d6ccb6ee7b08
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
string query = string.Empty;
string FileName = string.Empty;
string TableName = string.Empty;
string connstring = string.Empty;
string FolderPath = string.Empty;
string where = string.Empty;
string PackageName = "Error";
int SourceId = 0;
int BatchId = 0;
int flag = 0;
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
FolderPath = FolderPath+"\\";
//if (FolderPath.LastIndexOf("\\")="\\")
//{
// FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
//}
if (File.Exists(FolderPath + PackageName + "File.XLSX"))
{
File.Delete(FolderPath + PackageName + "File.XLSX");
}
if (FolderPath.Contains(".xlsx"))
{
FolderPath = FolderPath.Trim('\\');
FolderPath = FolderPath.Remove(FolderPath.LastIndexOf('\\') + 1);
}
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//Read distinct error euerries
query = "select distinct ErrorQuery, SheetName from ErrorMapping where FileType = 'PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
cmd.CommandText = query;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorMapping = new DataTable();
dt_ErrorMapping.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorMapping != null && dt_ErrorMapping.Rows.Count > 0)
{
foreach (DataRow dt_ErrorMapping_row in dt_ErrorMapping.Rows)
{
query = dt_ErrorMapping_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
Error(dt_ErrorMapping_row["SheetName"].ToString());
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::TempFolderPath"].Value.ToString() + "\\" +
"Error" + datetime + ".log"))
{
sw.WriteLine("Error Message: " + exception.Message.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
public void ExportExcelFile(DataSet ds, string connstring, string SheetName)
{
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//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_Cmd.CommandTimeout = 0;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table [" + SheetName + "] (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
Excel_OLE_Con.Close();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
bool firstRow = true;
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 + ") VALUES(";
int columnCount = table.Columns.Count;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.CommandTimeout = 0;
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].ToString() + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
}
}
public void Error(string ActualSheetName)
{
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//drop Excel file if exists
if (!string.IsNullOrEmpty(ActualSheetName))
{
//FileType='PremiumFile'"
query = "Select ErrorQuery,SheetName,FileType from pol.ErrorMapping Where SheetName = '" + ActualSheetName + "' and FileType='PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
foreach (DataRow dt_ErrorInfo_row in dt_ErrorInfo.Rows)
{
query = dt_ErrorInfo_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
//cmd.CommandTimeout = 600;
cmd.Connection = _connection;
cmd.CommandTimeout = 0;
_connection.Open();
DataTable dt_Actual_data = new DataTable();
dt_Actual_data.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
FileName = PackageName + dt_ErrorInfo_row["FileType"].ToString();
//TableName = "ErrorFileInfo ";
//Construct ConnectionString for Excel
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + FileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
string SheetName = "";
object[] array = dt_ErrorInfo_row.ItemArray;
SheetName = array[1].ToString();
//Load Data into DataTable from SQL ServerTable
//string queryString = "SELECT * from " + TableName + " ";
//OleDbDataAdapter adapter = new OleDbDataAdapter(query, _connection);
DataSet ds = new DataSet();
ds.Tables.Add(dt_Actual_data);
//adapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ExportExcelFile(ds, connstring, SheetName);
flag++;
}
}
}
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

Related

Import EXCEL with SSIS without knowing sheename

I'm trying to use SSIS to import multiple files from a folder, and i dont know the SheetName.
So, I'm creating a script task according to below link, to get SheetName, but i got error in the script task 'array size cannot be specified in a variable declaration'
http://www.anupamanatarajan.com/2011/01/dynamic-sheet-name-in-ssis-excel.html
public void Main()
{
// TODO: Add your code here
string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::BBGFilePath"].Value.ToString();
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
}
//Provide value to the shetename variable
Dts.Variables["User::SheetName"].Value = excelTables[0];
//Display file name
string strMessage = Dts.Variables["User::BBGFilePath"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}
So i tried to add the [User:SheetName] variable to the Script task, but it doesn't work.
can anyone please check what is missing?
As I had mentioned earlier, the error does clearly suggested you have some non-declaration statements at the class level which is not valid.
Your code from the script task have some issues with the closing brace --
public void Main()
{
// TODO: Add your code here
string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::BBGFilePath"].Value.ToString();
//Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\CESLtd\ELKAY\Reports\Work2\Book1.xls; Extended Properties = "EXCEL 8.0;HDR=YES";
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0;HDR=YES";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
//} **commented this line now you are good to go**
//Provide value to the shetename variable
Dts.Variables["User::SheetName"].Value = excelTables[0];
//Display file name
string strMessage = Dts.Variables["User::BBGFilePath"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}

C# Import Excel Data into Existing MDB Database

I have an Access MDB File with just one table simply called "Sheet1". Inside Sheet1 I already have the Fields Identified, but I left the table empty of any records.
I'm trying to copy data from a CSV file into the Access Sheet1 table.
The code below works if the table does not already exist, but I get an error at the AccessCommand.ExecuteNonQuery(); line that says
System.Data.OleDb.OleDbException: Table 'Sheet1' already exists.
How do I revise this code so that I can import the CSV data into an empty Table with Fields already identified?
using System.Data.OleDb;
string filename = "MyCSV.csv";
int result = 0;
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
string uploaderMDB = dirPath + "MyMDB.mdb";
OleDbConnection AccessConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + uploaderMDB);
AccessConnection.Open();
OleDbCommand AccessCommand = new OleDbCommand("SELECT * INTO [Sheet1] FROM [Text;FMT=Delimited;DATABASE=" + dirPath + ";HDR=No].[" + filename + "]", AccessConnection);
AccessCommand.ExecuteNonQuery();
AccessConnection.Close();
Try it this way.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
I found a solution (it requires XLSX instead though...) for anyone interested. It uses the
Microsoft.Office.Interop.Access reference instead of OleDb.
string filename = "MyXLSX.xlsx";
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
string uploaderMDB = dirPath + "MyMDB.mdb";
string fullPath = dirPath + filename;
Application _accessData = new ApplicationClass();
_accessData.Visible = false;
_accessData.OpenCurrentDatabase(uploaderMDB);
_accessData.DoCmd.OpenTable("SHEET1");
_accessData.DoCmd.TransferSpreadsheet(AcDataTransferType.acImport, AcSpreadSheetType.acSpreadsheetTypeExcel12, "Sheet1", fullPath, true, "MY_NAMED_RANGE");
_accessData.CloseCurrentDatabase();
_accessData.Visible = true;
_accessData.Quit(AcQuitOption.acQuitSaveAll);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_accessData);
_accessData = null;

Update Excel Cell using OLEDB

I want to update 1 cell in an Excel (xlsx) file using OLEDB.
I have attached my code.
The first time you run, it fills in the values because INSERT is working.
The second time you run, it APPENDS the values because the UPDATE fails, and my Catch performs an INSERT. My goal is to have the UPDATE command work. When the UPDATE command executes, I get an error message:
No value given for one or more required parameters.
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.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ConsoleApp3.Program.InsertCSVIntoSheet(String excelPath, String sheet, String csvPath) in C:\Users\jbendler.atlab\source\repos\ConsoleApp3\Program.cs:line 175
This code comes from a demo Console App. This is the program.cs file.
The main part of the code is located at the bottom of the InsertCSVIntoSheet method. The output xlsx file is simply a new workbook, unedited. The input file is simply a text file, named with a .csv extension, that contains the following separated by carriage-return/linefeed - so the file has 5 lines with one character per line:
ABCDE
Thanks.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
InsertCSVIntoSheet(#"c:\temp\book1.xlsx", "NewSheet", #"c:\temp\test.csv");
}
private static void InsertCSVIntoSheet(string excelPath, string sheet, string csvPath)
{
int column;
int row;
int pos;
bool done;
char readUntilChar;
string csvData;
string columnName;
string cell;
string excelSheetName;
List<Tuple<int, int, object>> values = new List<Tuple<int, int, object>>();
string connectionString = CreateOleDbConnectionStringForExcel(excelPath);
OleDbCommand oleDbCommand = new OleDbCommand();
decimal decimalTest;
DateTime dateTimeTest;
int status;
int numColumns;
// Put CSV in to row/column/value Tuples
using (StreamReader reader = new StreamReader(csvPath))
{
csvData = reader.ReadToEnd();
row = 1;
// Split the csv data by new line
foreach (string line in csvData.Split(new string[] { "\r\n" }, StringSplitOptions.None))
{
if (!string.IsNullOrEmpty(line))
{
column = 1;
pos = 0;
cell = string.Empty;
// Split each line by ',' to get each cell. A value wrapped in '"' can include a ','
while (pos < line.Length)
{
cell = string.Empty;
// Check the first character. If it is a '"' then we assume the cell is surrounded
// in '"' and do NOT include the '"' in the output to the excel cell.
if (line[pos] == '"')
{
readUntilChar = '"';
pos++;
}
else
{
readUntilChar = ',';
}
done = line[pos] == readUntilChar;
if (line[pos] == '"')
{
// Skip over second '"' for a blank ("")
pos++;
}
while (!done)
{
cell += line[pos++];
if (pos == line.Length || line[pos] == readUntilChar)
{
if (readUntilChar == '"')
{
// Skip the '"'
pos++;
}
done = true;
}
}
// Skip over the ','
pos++;
if (!string.IsNullOrEmpty(cell))
{
// Test the data to determine the type (check for decimal and DateTime).
if (decimal.TryParse(cell, out decimalTest))
{
values.Add(new Tuple<int, int, object>(row, column, decimalTest));
}
else if (DateTime.TryParse(cell, out dateTimeTest))
{
values.Add(new Tuple<int, int, object>(row, column, dateTimeTest));
}
else
{
// Write out the value as a string
values.Add(new Tuple<int, int, object>(row, column, cell));
}
}
column++;
}
}
row++;
}
}
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
excelSheetName = GetExcelSheetNames(connectionString).Where(n => n.ToUpper().StartsWith(sheet.ToUpper())).FirstOrDefault();
//Set the connection string to recognize the header and to operate in Update mode(IMEX= 0)
using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString.Replace("IMEX=1", "IMEX=0")))
{
oleDbConnection.Open();
oleDbCommand = new OleDbCommand();
oleDbCommand.Connection = oleDbConnection;
oleDbCommand.CommandType = CommandType.Text;
if (excelSheetName != null)
{
// Delete Sheet
oleDbCommand.CommandText = "DROP TABLE [" + sheet + "]";
status = oleDbCommand.ExecuteNonQuery();
}
else
{
excelSheetName = sheet + "$";
}
numColumns = values.Max(v => v.Item2);
oleDbCommand.CommandText = "CREATE TABLE [" + sheet + "](";
for (int index = 0; index < numColumns; index++)
{
oleDbCommand.CommandText += "Column" + index.ToString() + " CHAR(255), ";
}
oleDbCommand.CommandText = oleDbCommand.CommandText.Substring(0, oleDbCommand.CommandText.Length - 2) + ")";
status = oleDbCommand.ExecuteNonQuery();
}
using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString.Replace("IMEX=1", "IMEX=0")))
{
oleDbConnection.Open();
oleDbCommand.Connection = oleDbConnection;
// Write out new values
foreach (Tuple<int, int, object> tuple in values)
{
try
{
columnName = GetExcelColumnName(tuple.Item2) + (tuple.Item1 + 1).ToString();
oleDbCommand.CommandText = "UPDATE [" + excelSheetName + columnName + ":" + columnName + "] SET " + "F1" + " = '" + tuple.Item3.ToString() + "'";
status = oleDbCommand.ExecuteNonQuery();
}
catch (OleDbException oledbex)
{
oleDbCommand.CommandText = "INSERT INTO [" + excelSheetName + "] VALUES ('" + tuple.Item3.ToString() + "')";
status = oleDbCommand.ExecuteNonQuery();
}
}
}
}
}
private static List<string> GetExcelSheetNames(string connectionString)
{
OleDbConnection oleDbConnection = null;
DataTable dataTable = null;
List<string> excelSheetNames = null;
using (oleDbConnection = new OleDbConnection(connectionString))
{
oleDbConnection.Open();
dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
if (dataTable != null)
{
excelSheetNames = new List<string>(dataTable.Rows.Cast<DataRow>().Where(r => r["TABLE_NAME"].ToString().EndsWith("$") || r["TABLE_NAME"].ToString().EndsWith("$'")).Select(r => r["TABLE_NAME"].ToString().ToUpper()));
}
return excelSheetNames;
}
private static string CreateOleDbConnectionStringForExcel(string sourceFile)
{
var fileInfo = new FileInfo(sourceFile);
switch (fileInfo.Extension.ToUpper())
{
case ".XLS":
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;;Data Source='{0}';Extended Properties='Excel 8.0;HDR=No;IMEX=1'", sourceFile);
case ".XLSX":
case ".XLSM":
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;;Data Source='{0}';Extended Properties='Excel 12.0;HDR=No;IMEX=1'", sourceFile);
default:
throw new NotSupportedException("File type not supported.");
}
}
private static string GetExcelColumnName(int columnNumber)
{
string columnName = String.Empty;
int dividend = columnNumber;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
}
}

'External table is not in the expected format.' when reading excel(.xlsx) file which is saving in 2010 format?

when i am reading excel(2010) file, "External table is not in the expected format." error occurs. i am using Oledb connection to read excel file.please provide me best solution for this issue. thank you...
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;IMEX=1;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connectionstring))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
System.Data.DataTable dtExcelSchema;
dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string firstSheet = "";
int count = dtExcelSchema.Rows.Count;
conn.Close();
//Read Data from First Sheet
conn.Open();
DataTable dt = new DataTable();
var tempDataTable = (from dataRow in dtExcelSchema.AsEnumerable()
where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
select dataRow).CopyToDataTable();
dt = tempDataTable;
firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
if (!firstSheet.EndsWith("$"))
{
firstSheet = dt.Rows[0]["TABLE_NAME"].ToString() + "$";
}
cmd.CommandText = "select * from [" + firstSheet + "]";
string query1 = "SELECT count(*) FROM [" + firstSheet + "]";
cmd = new OleDbCommand(query1, conn);
cmd.CommandText = query1;
if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
{
string sheetName = firstSheet.Replace(" ", "").Replace("'", "");
string query = "SELECT * FROM [" + sheetName + "]";
dtnew.TableName = firstSheet;
OleDbDataAdapter oda = new OleDbDataAdapter(query, conn);
oda.Fill(dtnew);
}
}
catch (Exception ex)
{
}
}

Excel to dataTable

I need to fetch a sheet from excel to a datatable. I first tried with LinqToExcel library, but this fetched the large numbers from the excel sheet as exponential numbers. I'm talking about big numbers like "2352143523453452334544". Only if they are formated as text it would work ok.
After that i've tried this :
OleDbConnection con = null;
System.Data.DataTable dt = null;
System.Data.DataTable dataTable1 = new System.Data.DataTable();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + UploadFileName + ";Extended Properties=Excel 8.0;";
string sql_xls;
con = new OleDbConnection(conStr);
con.Open();
//OracleDataAdapter oda = new OracleDataAdapter();
//OracleCommand cmd = new OracleCommand("select * from [Sheet1$]", con);
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheetNames = new string[dt.Rows.Count];
int i = 0;
foreach (System.Data.DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString(); i++;
}
sql_xls = "SELECT * FROM [" + excelSheetNames[0] + "]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql_xls, conStr);
System.Data.DataSet myDataSet = new System.Data.DataSet();
dataAdapter.Fill(myDataSet, "ExcelInfo");
dataTable1 = myDataSet.Tables["ExcelInfo"];
This one returned the same values in the same conditions as null.
Isn't there a simple way to fetch data from a excel file as it is? No conversions, no nothing. Just take it all as a string, and put it into a datatable ?
This is what i used and it worked for me:
private DataTable LoadXLS(string strFile, String sheetName)
{
DataTable dtXLS = new DataTable(sheetName);
try
{
string strConnectionString = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
SQLConn.Open();
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
string sql = "SELECT * FROM [" + sheetName + "$]";
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(dtXLS);
SQLConn.Close();
}
catch (Exception)
{
throw;
}
return dtXLS;
}
But you can try to export to CSV as well:
LinqToCSV

Resources