OleDb scheme for excel workbook not showing rows in schema - oledb

I am trying to open an Excel workbook and read from a sheet. Pretty simple.
string sConnction = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"C:\\Users\\sstowe\\Documents\\Ranorex\\RanorexStudio Projects\\BottomLineII\\BottomLineII\\Widget.xls\";Extended Properties=\"Excel 12.0;HDR=NO\";";
string sSql = "Select * FROM Corporate";
OleDbConnection cn = new OleDbConnection(sConnction);
OleDbCommand command = new OleDbCommand(sSql, cn);
cn.Open();
// var reader = command.ExecuteReader();
// Get all Sheets in Excel File
var dtSheet = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
You see var reader... commented out as I examine. I received an error "The Microsoft Office Access database engine could not find the object 'Corporate'. where Corporate is the name of the sheet. Gee says I, did I make a mistake with the name or something? So I opened dtSheet to look. In the debugger, dtSheet is reporting 0 rows yet cn is reporting State of Open. So the workbook is being found. Can someone advise as to how to find the sheet?
Thank you.
S

Spreadsheet names always have a $ at the end and you chould bracket it so change your SQL to...
Select * From [Corporate$]
Sheet names with spaces are bounded by single quotes so a sheet called "Corporate Data" would be...
Select * From ['Corporate Data$']
You can have a look at the available sheets with...
DataTable dtTablesList = new DataTable();
dtTablesList = cn.GetSchema("Tables");

Related

How fetch image from database using Stream Classic?

I successful Adding image in SQL database using Stream class in that code
Public CN As New ADODB.Connection
Public Emp As New ADODB.Recordset
Public ST As New ADODB.Stream
Emp.Open("Employees", CN, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
Emp.AddNew()
ST.Open()
ST.Type = ADODB.StreamTypeEnum.adTypeBinary
ST.LoadFromFile(OpenFileDialog1.FileName)
Emp(19).Value = ST.Read
Emp.Update()
ST.Close()
Emp.Close()
this operation is successful but when I retrieve the database using this Code:
Emp.Open("Select * From Employees Where UserName = '" + TXTSearch.Text + "'", CN)
ST.Open()
ST.Type = ADODB.StreamTypeEnum.adTypeBinary
ST.Write(Emp.Fields(19).Value)
ST.SaveToFile("\temp", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
PICEmployee.Image = Image.FromFile("\temp")
ST.Close()
Emp.Close()
I have a button to show the database grid and it confirm the picture is loaded
but when I tried to fetch the data it stopped in that line
ST.SaveToFile("\temp", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
says Failed to Write I changed the Path got same error, I open the VB as Administrator got same error.
Tip: I didn't send All my Codes in case if something missing but everything about Stream is here
I like to have simple solution I'm still beginner and Need all Help you can give to me, Thanks

Using google sheets Need to automatically save or create a new sheet when the master is opened

This is my 1st time using Google sheets, I have a Master sheet set up for people to use, but I don't want them to have a chance to change the master and I don't trust them to create a copy before using the sheet.
I want people to start out opening the master but have the name changed after they open it and before they have the chance to make any changes.
The name of the new sheet should be the name used in the Master but add to it the current date.
The new sheet can be added to the current workbook
I don't want this to happen again if they sheet being created is opened later to modify or view the new sheet
I'm open to alternatives
The Google sheets api is fine to use
Please include examples of code or pointers to samples that all ready work
Thanks for the help
Found some code that started me down the right road, played with it until it did what I wanted. Only problem is that when you use the Google Sheet app on phone does not execute the onOpen code.
var ss = SpreadsheetApp.getActiveSpreadsheet();
/**
* Duplicate and rename Master spreadsheet invoking the makeCopy() function.
* The onOpen() function is automatically run when the spreadsheet is opened.
*/
function onOpen() {
var entries = [{
name: "Weekly Cashier Accounting",
functionName: "duplicateTemplateSheet"
}];
ss.addMenu("New sheet", entries);
var oldSheet = ss.getActiveSheet();
ss.setActiveSheet(ss.getSheetByName("Master"));
var formattedDate = Utilities.formatDate(new Date(), "PST", "MM-dd-yyyy");
if (ss.getSheetByName(formattedDate) == null) {
Logger.log("Does not exist");
var newSheet = ss.duplicateActiveSheet();
newSheet.activate();
ss.moveActiveSheet(2);
newSheet.setName(formattedDate);
ss.setActiveSheet(ss.getSheetByName(formattedDate));
}
};
Thanks for the help

New Google Spreadsheets publish limitation

I am testing the new Google Spreadsheets as there is a new feature I really need: the 200 sheets limit has been lifted (more info here: https://support.google.com/drive/answer/3541068).
However, I can't publish a spreadsheet to CSV like you can in the old version. I go to 'File>Publish to the web' and there is no more options to publish 'all sheets' or certain sheets and you can't specify cell ranges to publish to CSV etc.
This limitation is not mentioned in the published 'Unsupported Features' documentation found at: https://support.google.com/drive/answer/3543688
Is there some other way this gets enabled or has it in fact been left out of the new version?
My use case is: we retrieve Bigquery results into the spreadsheets, we publish the sheets as a CSV automatically using the "publish automatically on update" feature which then produces the CSV URL which gets placed into charting tools that read the CSV URL to generate the visuals.
Does anyone know how to do this?
The new Google spreadsheets use a different URL (just copy your <KEY>):
New sheet : https://docs.google.com/spreadsheets/d/<KEY>/pubhtml
CSV file : https://docs.google.com/spreadsheets/d/<KEY>/export?gid=<GUID>&format=csv
The GUID of your spreadsheet relates to the tab number.
/!\ You have to share your document using the Anyone with the link setting.
Here is the solution, just write it like this:
https://docs.google.com/spreadsheets/d/<KEY>/export?format=csv&id=<KEY>
I know it's weird to write the KEY twice, but it works perfectly. A teammate from work discovered this by opening the excel file in Google Docs, then File -> Download as -> Comma separated values. Then, in the downloads section of the browser appears a link to the CSV file, like this:
https://docs.google.com/spreadsheets/d/<KEY>/export?format=csv&id=<KEY>&gid=<SOME NUMBER>
But it doesn't work in this format, what my friend did was remove "&gid=<SOME NUMBER>" and it worked! Hope it helps everyone.
If you enable "Anyone with the link sharing" for spreadsheet, here is a simple method to get range of cells or columns (or whatever your feel like) export in format of HTML, CSV, XML, JSON via the query:
https://docs.google.com/spreadsheet/tq?key=YOUR-KEY&gid=1&tq=select%20A,%20B&tqx=reqId:1;out:html;%20responseHandler:webQuery
For tq variable read query language reference.
For tqx variable read request format reference.
Downside to this is that your doc is still availble in full via the public link, but if you want to export/import data to say Excel this is a perfect way.
It's not going to help everyone, but I've made a PHP script to read the HTML into an array.
I've added converting back to a CSV at the end. Hopefully this will help some people who have access to PHP.
$html_link = "https://docs.google.com/spreadsheets/d/XXXXXXXXXX/pubhtml";
$local_html = "sheets.html";
$file_contents = file_get_contents($html_link);
file_put_contents($local_html,$file_contents);
$dom = new DOMDocument();
$html = #$dom->loadHTMLFile($local_html); //Added a # to hide warnings - you might remove this when testing
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
$cols = $rows->item(0)->getElementsByTagName('td'); //You'll need to edit the (0) to reflect the row that your headers are in.
$row_headers = array();
foreach ($cols as $i => $node) {
if($i > 0 ) $row_headers[] = $node->textContent;
}
foreach ($rows as $i => $row){
if($i == 0 ) continue;
$cols = $row->getElementsByTagName('td');
$row = array();
foreach ($cols as $j => $node) {
$row[$row_headers[$j]] = $node->textContent;
}
$table[] = $row;
}
//Convert to csv
$csv = "";
foreach($table as $row_index => $row_details){
$comma = false;
foreach($row_details as $value){
$value_quotes = str_replace('"', '""', $value);
$csv .= ($comma ? "," : "") . ( strpos($value,",")===false ? $value_quotes : '"'.$value_quotes.'"' );
$comma = true;
}
$csv .= "\r\n";
}
//Save to a file and/or output
file_put_contents("result.csv",$csv);
print $csv;
Here is another temporary, non-PHP workaround:
Go to an existing NEW google sheet
Go to "File -> New -> Spreadsheet"
Under "File -> Publish to the web..." now has the option to publish a csv version
I believe this is actually creating an old Google sheet but for my purposes (importing google sheet data from clients or myself into R for statistical analysis) it works until they hopefully update this feature.
I posted this in a Google Groups forum also, please find it here:
https://productforums.google.com/forum/#!topic/docs/An-nZtjaupU
The correct URL for downloading a Google spreadsheet as CSV is:
https://docs.google.com/spreadsheets/export?id=<ID>&exportFormat=csv
The current answers do not work anylonger. The following has worked for me:
Do File -> "Publish to the web" and select 'start publishing' and the format. I choose text (which is TSV)
Now just copy the URL there which will be similar to https://docs.google.com/spreadsheet/pub?key=YOUR_KEY&single=true&gid=0&output=txt
That new feature appears to have disappeared. I don't see any option to publish a csv/tsv version. I can download tsv/csv with the export, but that's not available to other people with merely the link (it redirects them to a google docs sign-in form).
I found a fix! So I discovered that old spreadsheets before this change were still allowing only publishing certain sheets. So I made a copy of an old spreadsheet, cleared the data out, copy and pasted my current info into it and now I'm happily publishing just a single sheet of my large spreadsheet. Yay
I was able to implement a query to the result, see this table
https://docs.google.com/spreadsheets/d/1LhGp12rwqosRHl-_N_N8eTjTwfFsHHIBHUFMMyhLaaY/gviz/tq?tq=select+A,B,I,J,K+where+B%3E=4.5&pli=1
the spreadsheet fetches data from earthquake, but I just want to select MAG 4.5+ earthquakes so it makes the query and the columns, just a problem:
I cannot parse the result, I tried to decode as json but was not able to parse it.
I would like to be able to show this as HTML or CSV or how to parse this ? for example to be able to plot it on a Google Map.

MVC bulk upload for Arabic data

Im uploading excel file using sqlbulkupload
The file has Arabic data so it's inserted in the database like '??????' .
How can I solve this ? This is my code
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
sqlBulk.DestinationTableName = "StudentInfo";
sqlBulk.WriteToServer(dReader);
The most obvious answer would be to convert your database columns to nvarchar types. if they are varchar, they won't be able to hold unicode characters outside of the ascii range.
If they are already nvarchar in your database, try changing the connection string. This example is from a vb6 app, but may be helpful:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & ";Extended Properties=""Text;HDR=YES;CharacterSet=Unicode"""
Found here:
http://social.msdn.microsoft.com/Forums/windows/en-US/34efad11-bf82-4484-9904-107c3c39a302/reading-from-a-csv-or-a-txt-file-in-unicode-format

How can I read an uploaded Excel file and save it direct to DB?

Is there a way to upload an Excel file and save its content to Sql Server directly?
thanks!!
EDITED:
I don't want to save it as binary. I want to read its contend and save them to DB, each Excel column content into the DB table column and so on...
You can use something like this.. you need have oledb drive on your server.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + uploadFilenm + "; Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34;
// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);
// Open connection with the database.
objConn.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [sheet1$]", objConn);
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();
// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");
I know or a product called QueryCell that lets you use SQL to access an excell file. Not exactly what you were looking for but i thought it was woth mentioning.
you can make a dtsx package in SSIS that will treat the excel file as a data source - specify your SQL database as the data destination and you're away!
here: http://msdn.microsoft.com/en-us/library/ms139836.aspx

Resources