I'm trying to build some charts using xlsxwriter as shown in the following code, but I also get to use openpyxl before reaching out this code. The error is:
AttributeError: 'Workbook' object has no attribute 'add_chart'
I'm understanding that it's trying to run this with openpyxl instead of xlsxwriter, is there a way to unistall openpxl before running this part? or can i force it to run with xlsxwriter? or anyother way?
workbook = xlsxwriter.Workbook(output_path + '\\' + input)
worksheet = workbook.add_worksheet()
workbook = writer.book
worksheet = writer.sheets['New_Freq']
chart = workbook.add_chart({'type': 'column'})
chart.add_series ({'values': '=New_Freq!$A:$B'})
worksheet.insert_chart('G2', chart)
Related
I have an excel file that has a Bar Chart (Chart2) as a sheet named 'Output'. So I want to change the style format of Chart2 by using Openpyxl. However, I tried the simple code that did not work for me:
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Series, Reference
wb = load_workbook(r'C:\Users\sma.xlsx')
sheet1 = wb['Output']
Chart2 = BarChart()
print(Chart2)
Chart2.style = 6
wb.save(r'r'C:\Users\sma.xlsx')
wb.close()
Can anyone give me the right approach to get my proper result?
So, my question may sound silly because this is the first time I'm using XlsxWriter. I straight up copied their code from their site but it didn't work.
The code is this:
import pandas as pd
# Create a Pandas dataframe from the data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter objects from the dataframe writer object.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
workbook = xlsxwriter.Workbook('filename.xlsx')
worksheet = workbook.add_worksheet()
Even before I could start dealing with CSV files, this basic first run failed, and the following error appeared:
NameError: name 'xlsxwriter' is not defined
I tried using pip install openpyxl as someone said in this previous thread, but it didn't work either. Can someone give me a hand here please?
If you are going to use xlsxwriter directly, outside of Pandas, like you are doing in the last 2 lines of the code above, you will need to import the module in order to use it:
import xlsxwriter
# ... Rest of your code as above.
I'm using xlsxwriter to create an Excel file. Currently, I'm doing something like this:
import datetime
import pandas as pd
import xlsxwriter
workbook = xlsxwriter.Workbook('Test.xlsx')
worksheet = workbook.add_worksheet()
datetime_format = workbook.add_format({
'font_size': 12
})
worksheet.write('C2', datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), datetime_format)
# Rest removed for brevity. I simply have many stuff that
# I manually write to make the design as I want.
workbook.close()
writer = pd.ExcelWriter('Test.xlsx', engine='xlsxwriter')
result.to_excel(writer, startrow=6, startcol=3) # Start from D7.
writer.save()
Now, this seems to rewrite everything that I previously wrote manually using xlsxwriter. Also, I noticed that xlsxwriter does not have support by default to write data frames, am I right? How can I combine xlsxwriter and pandas to manually write some stuff to do Excel sheet, and then later to write all the data frame stuff starting from the specific cell?
You need to shift things around. I would also recommend to read the XlsWritter documentation on how to use it with pandas.
writer = pd.ExcelWriter('Test.xlsx', engine='xlsxwriter')
workbook = writer.book
result.to_excel(writer, sheet_name='Sheet1', index=False, startrow=6, startcol=3) # Start from D7.
worksheet = writer.sheets['Sheet1']
datetime_format = workbook.add_format({
'font_size': 12
})
worksheet.write('C2', datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), datetime_format)
writer.save()
First, we create our writer object using pd.ExcelWriter() and passing xlswriter as the engine. Once we have our writer we can access our workbook using the .book class vriable. At this time, we can write our data into our workbook using df.to_excel(). We will use the sheet_name argument of to_excel to create and name our worksheet. At this point we can acess our worksheet using the .sheets class variable and passing our sheetname as a key - in our case Sheet1.
From there you can write additional values to your sheet with or without using a pandas object - as shown in the code below.
I am new to Python and I was practicing by processing some CSV files and making an excel file from them. So far I can get the excel file however, I am unable to wrap the cells via python. I have tried multiple ways but none of it would work. Perhaps it is because of my poor understanding of Python. Can anyone suggest me how can I wrap text while writing the excel file? And please explain the code along the way? The error that i am getting for the following code is:
'str' object has no attribute 'alignment'
This is what I have done so far:
df=pd.DataFrame(list(zip(Dticketnumberlist,Dcategorylist)),
columns=['Ticket', 'Category'])
writer = pd.ExcelWriter('Trial Version.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook=writer.book
worksheet = writer.sheets['Sheet1']
wrap_alignment = Alignment(wrap_text=True)
cell.alignment = wrap_alignment
You can use pandas with the xlsxwriter engine (the default).
You need to create a format object by calling the workbook.add_format() method as outlined in the xlsxwriter docs (link here).
Once you've used pandas.DataFrame.to_excel(), you can add the format using worksheet.set_column(). An example of this can be found in the xlsxwriter docs (link here).
I've provided a fully reproducible example below with the expected output.
import pandas as pd
df = pd.DataFrame({'Ticket': ['a','b','c','d'],
'Category': [2,1,4,3]})
writer = pd.ExcelWriter('Trial Version.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook=writer.book
worksheet = writer.sheets['Sheet1']
format = workbook.add_format({'text_wrap': True})
# Setting the format but not setting the column width.
worksheet.set_column('A:B', None, format)
writer.save()
Expected Output:
Use python xlsxwriter
The question answered previously can help you better.
I am trying to load an existing Excel file and create a new sheet inside that workbook, but my code is not working using openpyxl.
rb = load_workbook("C:\Raw_Dump.xlsx")
rb.create_sheet("Sheet2")
sheet1 = rb.worksheets[0]
Any help would be appreciated.
You have to save the workbook to the same filename:
rb.save(r"C:\Raw_Dump.xlsx")
full working example:
import openpyxl
ws_name = r"Raw_Dump.xlsx"
rb = openpyxl.load_workbook(ws_name)
rb.create_sheet("Sheet2")
rb.save(ws_name)
I spent a long time searching this and found the best way is to do sheet removal. The code below worked for me:
for sheet in wb.sheetnames:
if sheet not in "MY_SHEET_I_WANNA_KEEP":
rm_sheet = wb[sheet];
wb.remove_sheet(rm_sheet)
wb.save("JustOneSheet.xlsx")