Answer the question
In order to leave comments, you need to log in
When outputting data to Excel from SQL, column names are not output?
Good afternoon!
I started learning Python and working with SQL and it became interesting if, let's say I have a text file, how to translate it into Excel via Python and work with it.
Initially, I decided to simply convert it into Excel and divide it into columns and cells, which after a while turned out.
Then I racked my brains for a long time on how to work with this file through Python, so that they would be immediately displayed with any changes to the file.
I found a solution to use the sqlite3 and pandas libraries and translate the file into a database format.
The solution is effective, but with one significant drawback. Since I did not find a way to work with the database, I can not see if the data was transferred from Excel to SQL correctly.
It seems that I have already downloaded a bunch of different things to work with the database, but I haven’t figured out how to work with any of them, and I don’t really want to. SQLite was the closest, but the problem is that I can’t find the program itself, there is only a console that I don’t need (if anyone tells me what to do next after installation, I will be very grateful).
Well, the main question: I decided to bypass this topic in such a way that I want to re-translate the resulting and modified database into an Excel file, because. As I understand it, when changes are made to the database, the original Excel file does not change, but I do not see any changes.
I found a solution on one of the sites and in practice it works, although I haven’t fully figured out what it does.
import sqlite3
import xlsxwriter
workbook = xlsxwriter.Workbook('xxx.xlsx')
worksheet = workbook.add_worksheet()
con1 = sqlite3.connect('xxx.db')
cur1 = con1.cursor()
cur1.execute("""SELECT * FROM xxx;""")
my_select = cur1.execute("""SELECT * FROM xxx;""")
for i, row in enumerate(my_select):
for j, value in enumerate(row):
worksheet.write(i, j, row[j])
workbook.close()
Answer the question
In order to leave comments, you need to log in
First, figure out what exactly is happening in the above code. Directly write down line by line to yourself what is being done and why.
And then you need to add a line entry with the column names to this code before writing the columns themselves.
Column names can be obtained from the database with a query like:
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question