Export data from Oracle SQL Developer to Excel .xlsx - sql

I have a small project where data from Oracle SQL Developer needs to be exported to Excel (using commands rather than tools in SLQ Developer), then create a graph.
Using "spool" I can export to csv fine (but cant make a graph in csv) but when I try to export to xlsx it corrupts the whole excel sheet saying
"Excel cannot open the file "ExcelFile.xlsx" because the file format or file extention
is not valid. Verify that the file has not been corrupted and that the
file extension mathces the format of the file."
Here is the code I used in SQL Developer.
spool FileLocation\ExcelFile.xlsm
SELECT * FROM Table;
spool off;
Is there any way I can stop the data from becoming corrupted or is there another way to export data to a .xlsx file?

Nooooooo.
set sqlformat csv
spool c:\file.sql
select * from table;
spool off;
then open the file in excel.
OR
Run your query interactively.
Right click on the grid, Export > XLSX. Open the file.
Spool only writes the query output to the file, it doesn't look at the file extension and figure out HOW to write the output at that point.
So you either have to code it yourself via the query, or use one of the format outputs we support
SET SQLFORMAT
CSV
JSON
DELIMITED
XML
HTML
INSERT
LOADER
Use 'help set sqlformat' for help.

Hi sql developer from what I know for exporting is using sqlplus(code is same) so perhabs there are other ways but this one should be good enough
I would try changing first line to look like this:
spool ExcelFile.xls
Probably you also need to turn on
SET MARKUP HTML ON
http://www.orahow.com/2015/09/spool-sqlplus-output-to-excel-format.html
Anyway there is workaround - you can just generate .CSV file and then open it in excel and save as .xlsx file

I was also facing the same problem then applied below code and it exported successfully..
import xlsxwriter
from xlsxwriter import Workbook
import cx_Oracle
import datetime
from datetime import date
dsn_tns = cx_Oracle.makedsn('HOST', 'PORTNO', sid='BGRDB')
db = cx_Oracle.connect(user=r'username', password='password', dsn=dsn_tns)
cursor = db.cursor()
workbook = xlsxwriter.Workbook('C:/Path/outfile.xlsx')
sheet = workbook.add_worksheet()
cursor.execute("select * from TABLENAME")
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
sheet.write(r, c, col)
workbook.close()
cursor.close()

Related

How to fix Encoding error utf-8 - PostgreSQL

I am following instructions online to create a database in pgAdmin4. I have successfully imported a csv file and created a table. However, I cannot select anything from the table.
My code is:
SELECT * FROM transfers;
Error message is: 'utf-8' codec can't decode byte 0xc3 in position 0: unexpected end of data
Running 'show server_encoding' gives "UTF8" in the output.
Running 'show client_encoding gives "UNICODE" in the output.
Maybe you saved an excel file as csv and imported to postgre, if so, open excel, create a blank csv file and copy/paste your excel data to there and save. Delete your previous postgre table and import newly created csv file again.

DataTable.ImportSheet operation failed.Invalid file

I'm running Excel tests on UFT and sometimes I get the error number 20012 which is "DataTable.ImportSheet operation failed.Invalid file".
This is my way of importing the script:
DataTable.ImportSheet filepath,scriptname,"Action2"
filepath is the path of my workbook which conatins many excel sheets (scripts)
scriptname: the name of the script that I want to run
Action2: contains all the call of all possible keywords that may script can contains.
Any help please, why I'm getting this error.
The problem is that this is working well for some scripts and for others not after 3 or 4 run times.
I think the problem is on Excel itself and not on the code, are there any problems when working with Excel 2016 and UFT 12 ?
UFT syntax for importing a worksheet is:
DataTable.ImportSheet FileName, vtSrcSheet, vtDstSheet
This means you need to pass as parameters the filename (and path) to the excel file, the name (or index) of the source sheet you want to import, and then the destination you want this sheet to be (for example "Global" or "Action1" etc)
Unless scriptname happens to be the exact name of the worksheet you are trying to import you will get this error.
If you want to import the whole file use Datatable.Import instead of Datatable.ImportSheet

Export Access Query WITHOUT Formatting

Relatively simple, but I can't seem to work it out. I want to export a query from access into a .csv (tab or comma delimited). When I do it manually through the wizard it works fine. But when I do it via vba, it comes complete with dash formatting that looks like the borders in the table!
I tried two methods and got the same results
DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen
I used it with or without "ExportSpec", which is a specification I created when exporting manually.
This is the second method:
Dim testSQL As String
Dim qd As DAO.QueryDef
testSQL = "SELECT * FROM Qry_Grade"
Set qd = db.CreateQueryDef("tmpExport", testSQL)
DoCmd.TransferText acExportDelim, , "tmpExport",_
"C:\Users\Databoe\Documents\KidsTV\grade.csv"
db.QueryDefs.Delete "tmpExport"
This is a solution I've found which seems like overkill
And this is what the output looks like:
You can see it's not actually split any of the columns when opening the file in excel and that every second line is just a string of "-"'s
What about DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, myQueryName, myExportFileName, True for direct excel file export.
I tried your approaches, but I only get formated text with your first try DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen which is as expected because it's a text export not csv.
With your second method I always get an excel compatible result. Maybe you have an error trap that hides an error and the first grade.csv is not overwritten. Use a different filename for the second method to prevent that.
Found a second trap. You don't specify full file path in first method, but in second. If C:\Users\Databoe\Documents\KidsTV is not your default document path, you have 2 grade.csv in different folders, but you maybe think that you only have one that gets overwritten.
I just ran into this problem myself, and found a great work around. It doesn't save as a .csv, but you can save as a comma delimited .txt file.
Use the export wizard on the External Data tab to export your query as a .txt file without formatting.
Once the file is exported you get a dialogue box asking if you want to save export steps. Click the box and save the export.
There is an action available in the Macro wizard called "Run Saved Import/Export." Select this action and choose your saved export from the dropdown menu.
Very frustrating that even now I cant seem to make Access export a simple csv file. I do not know why they think I need pretty formatting. Try this: open Excel, Click Get Data, From Database, From MicroSoft Access Database. Select the Access Database you wish to export from. Select the table/query we want saved as an csv. This will set up a link to this table. Once imported, save the Excel file to an csv file.

Data Import from SQL server to Excel sheet SSIS

I'm working on a data export package where I move few data from sql to a excel sheet.
This package is automated to execute every weekend .
Unless i delete the previous excel file , I'm not able to run the package again as it throws the destination table is already present error.
Suggest me a way to retain the old excel file and create a new one everytime.
For example , if the earlier excel sheet was named export_1 , the next sheet on the subsequent week should be named export_2
Create 2 parameteres
File_Path
Connection_String
2.Use a Script task that creates an Excel File and Assign the values to
parameters "File_Path" and "Connection_String" based on the newly
created Excel file
Parameterize the 'Excel Connection'
ConnectionString --> Connection_String
ExcelFilePath --> File_Path
You can dynamically pass the file name through the expressions based on the Datetime.
Ex: Filepath+Date1_mmddyy_hhmmss
Every time the file generates, It will create a file with new file name and Excel file should be passed as an expression.

XLS to CSV Powershell Conversion, maintaining decimal points/precision

I'm trying to convert an XLS file into CSV using Excel as a ComObject, yet maintaining the precision of the data concerned. I've tried changing the style to "#" or "Text" or similar for the formatting of each cell, but this still results in limited precision and doesn't seem to apply to the whole file.
For example: cell D4 in my source xls document has a value of 0.5124839309949 but is viewed as 0.51 due to Excel's Number formatting. Manually changing this to Text formatting resolves this but I need Powershell to run this for me, and then export (in CSV format) that same 0.5124839309949 rather than 0*.*51.
At the same time, I'm concerned about how this will treat date cells. As it stands, each row in my array has a date which Excel reads as DD/MM/YYYY except when put through to CSV this becomes the Excel serial date number (useless for my ultimate goal of bulk loading this into SQL Server.)
I'm aware that a File-SaveAs exercise in Excel produces a CSV but I need this to be run through Powershell due to business demands, and also, running this 'conversion' exercise manually also results in precision limits, so I am looking for a way around this please.
If you're able to amend the below Powershell script I'd be grateful!
Thanks for your help.
#
# Set the current folder path to temp
Set-Location \\xyz01\data\shared\data_warehouse\ntrs\temp
#Backup files
Copy-Item -path *.* -recurse \\xyz01\data\Shared\data_warehouse\test\performance
# Set variables
$file = "ABC Trust*"
$infile = "\\xyz01\data\shared\data_warehouse\ntrs\temp\"+$file
$outfile = "\\xyz01\data\shared\data_warehouse\test\temp\test_performance.csv"
# Set com object to Excel
$Excel = New-Object -ComObject Excel.Application
# Open the excel file and save as CSV
$workbook=$Excel.Workbooks.Open($infile)
$worksheet=$workbook.Worksheets.Item(1)
$worksheet.range.("D") = $worksheet.range.("D").Text
$workbook.SaveAs($outfile,6) # 6 is the code for .CSV
$workbook.Close($false)
$Excel.Quit()
The below may help? I have tried to replicate all suggested in here, to no avail.
Posh2Scripting - Automating Excel Spreadsheets with Powershell
Stackoverflow - Convert XLS to CSV without Data changes
OzGrid - Convert Excel To Text/CSV Without Losing Decimal Accuracy
Try changing this line...
$worksheet.range.("D") = $worksheet.range.("D").Text
to this...
$worksheet.range.("D") = $worksheet.range.("D").Value