With the following code, I manage to create excel files for each of the Country's but I am not able to format excel columns:
df=TOT.reset_index()
for n, g in df.groupby('Country'):
X = n.strip(" ")
out_path = "C:/temp/" + n.strip(" ") + ".xlsx"
C =TOTSPPerc.reset_index(level=0)[TOTSP.reset_index(level=0).Country==n].drop('Country', axis=1)
B =TOTPerc.reset_index(level=0)[TOTPerc.reset_index(level=0).Country==n].drop('Country', axis=1)
A= TOTcntPerc.drop('Country', axis=1)
writer = pd.ExcelWriter(out_path , engine='xlsxwriter')
format2 = workbook.add_format({'num_format': '0%'})
A.to_excel(writer, sheet_name="Country")
B.to_excel(writer, sheet_name="Stores")
C.to_excel(writer, sheet_name="SPs")
writer.save()
print(n)
I need to format column B:F for each of the 3 sheets for each of the created files.
You can set custom format to each sheet:
for n, g in df.groupby('Country'):
print (g)
#your code
writer = pd.ExcelWriter(out_path , engine='xlsxwriter')
A.to_excel(writer, sheet_name="Country")
B.to_excel(writer, sheet_name="Stores")
C.to_excel(writer, sheet_name="SPs")
workbook = writer.book
worksheet1 = writer.sheets['Country']
worksheet2 = writer.sheets['Stores']
worksheet3 = writer.sheets['SPs']
format2 = workbook.add_format({'num_format': '0%'})
worksheet1.set_column('B:F', 18, format2)
worksheet2.set_column('B:F', 18, format2)
worksheet3.set_column('B:F', 18, format2)
writer.save()
And more dynamic solution:
for n, g in df.groupby('Country'):
print (g)
#your code
writer = pd.ExcelWriter(out_path , engine='xlsxwriter')
dfs = [A,B,C]
sheetnames = ['Country','Stores','SPs']
for i, df1 in enumerate(dfs):
df1.to_excel(writer, sheet_name=sheetnames[i])
workbook = writer.book
worksheet1 = writer.sheets[sheetnames[i]]
format2 = workbook.add_format({'num_format': '0%'})
worksheet1.set_column('B:F', 18, format2)
writer.save()
Related
I'm trying to center the table content using df.style.set_properties(**{'text-align': 'center'}). But I couldn't do it. Is there any other way?
Here is the full code:
import pandas as pd
import time
subject = 'demo'
checked_names = ['First','Second']
checked_ID = [64,65]
index =[i+1 for i in range(len(checked_names))]
df = pd.DataFrame(list(zip(index, checked_names, checked_ID)), columns=['Index','Student Name','Student_ID'])
path = (r"C:\Users\heman\Desktop\Attendance_list")
file_name = (path + "/" + subject +"("+time.strftime("%d.%m.%Y_%H.%M")+")"+ "_" + "attendance.xlsx")
sheet_name = "sheet1"
writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name, startrow = 4, index = False)
for column in df:
column_width = max(df[column].astype(str).map(len).max(), len(column))
col_idx = df.columns.get_loc(column)
writer.sheets[sheet_name].set_column(col_idx, col_idx, column_width)
workbook = writer.book
worksheet = writer.sheets[sheet_name]
worksheet.write(0, 0, 'Attendance report of '+subject+' class', workbook.add_format({'bold': True, 'color': '#E26B0A', 'size': 14, 'align': 'left'}))
worksheet.write(2, 0, 'Date: '+time.strftime("%d/%m/%Y"))
worksheet.write(2, 3, 'Time: '+time.strftime("%r"))
df.style.set_properties(**{'text-align': 'center'})
writer.save()
Here is the excel file after executing
I usually use openpyxl for alignments or Excel formatting operations.
You could run something similar to this at the end of your code ( adapting the filename path, sheet name and desired cells you wish to align)
from openpyxl import load_workbook
from openpyxl.styles import Alignment
wb = load_workbook(filename = r'Attendance_list.xlsx')
mysheet = wb['Sheet1']
for row in range(1,mysheet.max_row+1):
for col in range(1,mysheet.max_column+1):
cell=mysheet.cell(row, col)
cell.alignment = Alignment(horizontal='center', vertical='center')
wb.save(r'Aligned.xlsx')
I am using the Coinmarketcap REST Api for having the latest cryptocurrency categories.
The code prints the JSON response into a DataFrame which is used for the transfer to excel (df.to_excel). Im using the "for column in df" for a bigger width in excel.
Now I would like to know how I can add costum column headings into the excel sheet.
def Cryptocurrencies():
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/categories'
parameters = {
}
headers = {
'Accept': 'application/json',
'X-CMC_PRO_API_KEY': 'mypersonalapikey',
}
session = Session()
session.headers.update(headers)
data = session.get(url, params=parameters)
response = session.get(url, params=parameters)
f = (json.loads(response.text)['data'])
df = pd.DataFrame(f)
writer = pd.ExcelWriter("Workingpaper1D.xlsx",
engine='xlsxwriter',
datetime_format='mmm d yyyy hh:mm:ss',
date_format='mmmm dd yyyy')
df.to_excel(writer, sheet_name='Sheet1',
startrow=1, header=False, index=False, )
(max_row, max_col) = df.shape
worksheet = writer.sheets['Sheet1']
worksheet.autofilter(0, 0, max_row, max_col - 1)
for column in df:
column_length = max(df[column].astype(str).map(len).max(), len(column))
col_idx = df.columns.get_loc(column)
writer.sheets['Sheet1'].set_column(col_idx, col_idx, column_length)
writer.save()
print(df)
return
You can set a custom header like this:
# Convert the dataframe to an XlsxWriter Excel object. Note that we turn off
# the default header and skip one row to allow us to insert a user defined
# header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
'bold': True,
'text_wrap': True,
'valign': 'top',
'fg_color': '#D7E4BC',
'border': 1})
# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num + 1, value, header_format)
See also this section of the XlsxWriter docs on Formatting of the Dataframe headers.
Hello I have data in list of dicts. I'm using panda DataFrame to parse from dict to excel. Data are fetch 5 different places. I would like to add data into different spreadsheet.
Here is the code I'm trying, but it doesn't add new sheets, it overwrites
def write_xlsx(filename, sheetname, data):
workbook = xlsxwriter.Workbook(filename)
checksheet = workbook.get_worksheet_by_name(sheetname)
if checksheet is None:
worksheet = workbook.add_worksheet(sheetname)
# Store the worksheet objects in a dict indexed by name.
my_worksheets = {}
for worksheet in workbook.worksheets():
my_worksheets[worksheet.get_name()] = worksheet
df = pd.DataFrame(data)
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheetname, index=False, startrow=1, header=False)
# Set the column widths
workbook = writer.book
worksheet = writer.sheets[sheetname]
header_format = workbook.add_format({'text_wrap': True})
columns_format = workbook.add_format({'text_wrap': True})
# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num + 0, value, header_format)
writer.save()
I've been using XLSXWriter on my Python/Flask app to export dataframes to Excel. Until today, I managed to export my dataframes on one worksheet; now I'm trying to export multiple dataframes on different worksheets inside one single file.
When I try locally (see first code attached), everything works perfectly. But when I write to an IOStream, I receive the following error:
TypeError: invalid file: None
Here is the functional local code:
path_user = expanduser("~").split("\\")[-1]
xlsx_path = r"C:\Users\{}\Desktop\ExportAllGraphs2.xlsx".format(path_user)
writer = pd.ExcelWriter(xlsx_path, engine='xlsxwriter')
count = 0
for df in df_list:
sheet_title = df["title"].split(' ', 1)[0]
sheet_name = "{}_{}".format(count, sheet_title)
df_header.to_excel(writer,startrow = 0, merge_cells = False, sheet_name = sheet_name)
df["df"].to_excel(writer,startrow = len(df_header) + 5, merge_cells = False, sheet_name = sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]
format = workbook.add_format()
format.set_bg_color('#eeeeee')
worksheet.set_column(0,50,20)
worksheet.write(len(df_header) + 4, 1, df["title"])
count += 1
writer.close()
os.system('start excel.exe "{}"'.format(xlsx_path))
and here is the non-functioning live code:
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
count = 0
for df in df_list:
sheet_title = df["title"].split(' ', 1)[0]
sheet_name = "{}_{}".format(count, sheet_title)
df_header.to_excel(writer,startrow = 0, merge_cells = False, sheet_name = sheet_name)
df["df"].to_excel(writer,startrow = len(df_header) + 5, merge_cells = False, sheet_name = sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]
format = workbook.add_format()
format.set_bg_color('#eeeeee')
worksheet.set_column(0,50,20)
worksheet.write(len(df_header) + 4, 1, df["title"])
count += 1
writer.close()
output.seek(0)
return send_file(output,
attachment_filename="test_export_{}.xlsx".format(current_date),
as_attachment=True)
Am I missing anything?
I'm saving pandas DataFrame to Excel with xlsxwriter. First I'm adding some format to columns (change font, for instance). Then I want to change background color for some rows. But when I add set_row function, all my column's format is gone. Is there a way to combine it?
import pandas as pd
data = pd.DataFrame({'test_data': [1,2,3,4,5]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
pd.core.format.header_style = None
data.to_excel(writer, sheet_name='test', index=False)
workbook = writer.book
worksheet = writer.sheets['test']
font_fmt = workbook.add_format({'font_name': 'Arial', 'font_size': 10})
worksheet.set_column('A:A', None, font_fmt)
zebra = workbook.add_format({'bg_color': 'green'})
for index in range(5):
if index % 2 == 0:
worksheet.set_row(index+1, None, zebra)
writer.save()
This shall help:
import pandas as pd
data = pd.DataFrame({'test_data': [1,2,3,4,5]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
pd.core.format.header_style = None
data.to_excel(writer, sheet_name='test', index=False)
workbook = writer.book
worksheet = writer.sheets['test']
formatdict = {'font_name': 'Calibri', 'font_size': 10, 'font_color':'red'}
font_fmt = workbook.add_format(formatdict)
worksheet.set_column('A:A', None, font_fmt)
zebra = workbook.add_format(formatdict)
zebra.set_bg_color('green')
for index in range(1,6,2):
worksheet.set_row(index, None, zebra)
writer.save()
Shall produce the following output: