I need to enter data's in a particular column in excel using python.
I am new to python and i am eager to involve with this scripting.
I expect the script that ask for a dialog to enter the data and the given data should import in the excel in the particular column.Can anyone help me?
You shall use openpyxl to manipulate excel.
Example:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "Sheet Name"
ws['B2'] = "Test Data 1"
# or
d = ws.cell(row=1, column=2, value="Test Data 2")
wb.save('D:\\Prabhakar\\Sample\\balances.xlsx')
Ref: Openpyxl
Related
What is the correct way to import specific sheet of excel by using Django-Import-Export Module??
or if possible. all the sheets in a workbook one by one...
I referred their documentation and it was not much helpful
https://django-import-export.readthedocs.io/en/latest/
the same way I would like to export data into one workbook from multiple sheets...
how do achieve it??
Here is the complete answer for my question
databook = Databook()
imported_data= databook.load(file.read( ), format= 'xlsx')
for dataset in imported_data.sheets():
print(dataset.title) # returns the names of the sheets
print(dataset) # returns the data in each sheet
This is how you can export your multiple datasets in one excel file
book = tablib.Databook((data1, data2, data3))
with open('students.xls', 'wb') as f:
f.write(book.export('xls'))
documentation
You can also try using use pyexcel_xls package on django it's fairly easy to use.
from pyexcel_xls import get_data as xls_get
def import_excel(request):
excel_file = request.FILES['file']
#uploading the excel file
if (str(excel_file).split('.')[-1] == "xls"):
data = xls_get(excel_file, column_limit=15)
elif (str(excel_file).split('.')[-1] == "xlsx"):
data = xlsx_get(excel_file, column_limit=15)
if (len(data['sheet1']) > 2): #reading of records begins from second row
name = data['sheet1'] #excel sheet name you wish to get
for l in range(2, len(name)): #loop through the number of rows in the sheet
data = name[l][0] #extract the first column's data
I am exporting data to excel(.xls) in django using xlwt module but datetime is exporting in this 43239.6389467593 format. I dont know what is this format and how to change it to datetime in excel sheet. I followed the following
https://simpleisbetterthancomplex.com/tutorial/2016/07/29/how-to-export-to-excel.html
This is a numerical representation of the date value. If you don't want to change the export code on django you can fix the issue within Excel.
If you have an entry like this in cell A1 for example then set Cell B1 =A1 and change the format of the cell B1 to the Dateformat you want. It should then appear as a normal date.
You can do this
import datatime
if isinstance(row[col_num], datetime.datetime):
date_time = row[col_num].strftime('%Y-%m-%d %H:%M:%S')
ws.write(row_num, col_num, date_time, font_style)
else:
ws.write(row_num, col_num, row[col_num], font_style
I am using xlsxwriter to export the contents of my database from Django admin to an Excel file. The headers in the Excel file are supposed to be my model field names, followed by the rows of data from my db. I've gotten the export process to work, however when I open the downloaded Excel file it shows all the columns/data from my database in a seemingly random order. They do not appear in the same order as the fields as seen in Django admin. In Django admin the info displays in the proper order of a table,
Column A - Column B - Column C - Column D - Column E - etc.
whereas in my exported Excel file I am seeing it all scrambled up,
Column B - Column E - Column A - Column D - Column C - etc.
Here is my code. I don't understand why it wouldn't be exporting the column names and data in the right order. Any help appreciated!
def dump_attorneys_to_xlsx(request):
if request.GET.get('export'):
output = BytesIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet('Summary')
attorneys = Attorney.objects.all().values()
# Write header
worksheet.write_row(0, 0, attorneys[0].keys())
# Write data
for row_index, row_dict in enumerate(attorneys, start=1):
worksheet.write_row(row_index, 0, row_dict.values())
workbook.close()
output.seek(0)
response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=summary.xlsx'
return response
else:
return render("change_list.html",
context_instance=RequestContext(request),
template_name='change_list.html')
values() returns rows as a list of dictionaries. In Python dictionaries are unordered.
This writes to the first sheet but all other sheets are blank.
for date in dates:
sheet = wb.add_worksheet(date)
sheet.write(row, 0, 'example')
For each date I want to creat a sheet with the name equal to the date and then write to each sheet. The sheets are created with the correct names but there is nothing in them except for the first sheet.
I supposed that your variable wb is the workbook and is initialized before.
In the instruction
sheet.write(row, 0, 'example')
I don't know how row is enhanced.
So i created a little script:
import xlsxwriter
list_name = ["first sheet", "second sheet", "third sheet"]
workbook = xlsxwriter.Workbook(<Your full path>)
for sheet_name in list_name:
worksheet = workbook.add_worksheet(sheet_name)
worksheet.write('A1', sheet_name)
workbook.close()
Regards
This is the code snippet which is working fine for me.you can replace the normal integers in the list with the dates.It is creating multiple sheets and writing into all sheets also.
import xlwt
List=[1,2,3,4]
book = xlwt.Workbook(encoding = "utf-8")
for i in List:
sheet1=book.add_sheet(str(i))
sheet1.write(0,0,"Example")
book.save("Test_Status.xls")
I'm trying to make a progress bar reflecting pandas dataframe build progress from sql. Currently I have a table with 9 columns containing 1000 records.
import pandas as pd
import psycopg2 as ps
import pandas.io.sql as psql
conn = ps.connect(user="user", password="password", database="database")
sql = "select * from table"
a = datetime.datetime.now()
df = psql.read_frame(sql, con=conn)
---and blablabla some little functions
b = datetime.datetime.now()
print b-a
instead of getting delta start & end time of the function, I would prefer and it would be nice to show progress bar to end user (just in case the data is getting bigger), so they have idea how long it would take. Is that possible? how to do it?