I am able to create vertical bar chart with below code:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for i in range(10):
ws.append([i])
from openpyxl.charts import BarChart, Reference, Series
values = Reference(ws, (1, 1), (10, 1))
series = Series(values, title="First series of values")
chart = BarChart()
chart.append(series)
ws.add_chart(chart)
wb.save("SampleChart.xlsx")
Can I create vertical bar chart with openpyxl? And export the same in image form?
The best chart support is currently in the excellent Xlsxwriter library. Improvements are coming to openpyxl, but as long as you only need to write files then Xlsxwriter is currently the best library.
As both libraries only generate the XML files, you cannot export the chart as an image. You might be able to this by remote control using xlwings but otherwise you should look at one of the visualisation libraries such as MatPlotLib.
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?
I tried to insert a column into an excel.
However, the style of cells has been changed
CODE:
import openpyxl
wb = openpyxl.load_workbook('xt3.xlsx')
sheet = wb.worksheets[0]
sheet.insert_cols(0)
[enter image description here][1]wb.save("filename.xlsx")
https://i.stack.imgur.com/hl5QY.png
issues on bitbucket: https://bitbucket.org/openpyxl/openpyxl/issues/1098/bugs-insert_cols-changes-merge-cells-and
After some digging I wrote this code in openpyxl and xlrd/xlwt/xlutils.
Support both xls and xlsx.
Before
After
The key is to use copy and generate coordinate.
Code is here
This code will insert 3 columns; It keeps the background color but not all of the borders.
merged_cells_range = ws.merged_cells.ranges
for merged_cell in merged_cells_range:
merged_cell.shift(3,0)
ws.insert_cols(1,3)
I would like to change the background color of a chart, as in this example, using openpyxl.
In a google group discussion I found the following code snippet:
from openpyxl.chart.shapes import GraphicalProperties
props = GraphicalProperties(solidFill="999999")
chart.graphical_properties = props
chart.plot_area.graphical_properties = props
but it does not have any effect on the chart when saved to the excel file.
This functionality was seemingly broken in a previous version of openpyxl and is fixed as of release 2.4.7. To achieve the result as illustrated in your picture you need to change the solid fill color of the plot_area:
from openpyxl import Workbook
from openpyxl.chart import BarChart
from openpyxl.chart.shapes import GraphicalProperties
wb = Workbook()
ws = wb.active
chart = BarChart()
props = GraphicalProperties(solidFill="999999")
chart.plot_area.graphicalProperties = props
ws.add_chart(chart, "A1")
wb.save("bar.xlsx")
Please note: the member object holding the graphical properties of chart is chart.graphical_properties, whereas in plot_area it is named plot_area.graphicalProperties - which is itself an alias for plot_area.spPr.
You need to be sure to access the proper member to create a valid data structure that does look as you expect it to in the Excel file.
I am using xlsxwriter to add charts to different worksheets in ipython and everything works, except my graphs are never showing up in the worksheets. There are no error messages.
When I tested the code from the documentation I also get a empty excel workbook.
I've tried it with xlsxwriter.Workbook and pd.ExcelWriter('test.xlsx', engine='xlsxwriter') but with both the workbook generates but no graphs are added.
How can I make the graphs show up?
Code from the documentation:
http://xlsxwriter.readthedocs.org/en/latest/working_with_charts.html
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
# Add the worksheet data to be plotted.
data = [10, 40, 50, 20, 10, 50]
worksheet.write_column('A1', data)
# Create a new chart object.
chart = workbook.add_chart({'type': 'line'})
# Add a series to the chart.
chart.add_series({'values': '=Sheet1!$A$1:$A$6'})
# Insert the chart into the worksheet.
worksheet.insert_chart('C1', chart)
workbook.close()
The results for
print(xlsxwriter.version)
0.5.7
print(zipfile.ZipFile("chart_line.xlsx").namelist())
['xl/worksheets/sheet1.xml', 'xl/workbook.xml', 'xl/charts/chart1.xml', 'xl/drawings/drawing1.xml', 'docProps/app.xml', 'docProps/core.xml', '[Content_Types].xml', 'xl/styles.xml', 'xl/theme/theme1.xml', '_rels/.rels', 'xl/_rels/workbook.xml.rels', 'xl/worksheets/_rels/sheet1.xml.rels', 'xl/drawings/_rels/drawing1.xml.rels']
There haven't been any reported issues of charts not displaying in Excel in any version of XlsxWriter that supported charts.
There are also almost 300 chart comparison tests in the XlsxWriter codebase that test the charts that it produces byte for byte against files produces by Excel. These are all passing.
Also, the output from zipfile in your post clearly shows the chart elements are there. If they were present but incorrect Excel would complain when it loaded the file.
And the code that you link to has a screenshot of the output that clearly shows a chart.
I also ran the code and see the chart in 3 versions of Excel and 1 version of LibreOffice.
So you need to go back and verify your results. If you think there is an issue then create a small working program that demonstrates it and submit a bug report.
I have been trying to generate data in Excel.
I generated .CSV file.
So up to that point it's easy.
But generating graph is quite hard in Excel...
I am wondering, is python able to generate data AND graph in excel?
If there are examples or code snippets, feel free to post it :)
Or a workaround can be use python to generate graph in graphical format like .jpg, etc or .pdf file is also ok..as long as workaround doesn't need dependency such as the need to install boost library.
Yes, Xlsxwriter[docs][pypi] has a lot of utility for creating excel charts in Python. However, you will need to use the xlsx file format, there is not much feedback for incorrect parameters, and you cannot read your output.
import xlsxwriter
import random
# Example data
# Try to do as much processing outside of initializing the workbook
# Everything beetween Workbook() and close() gets trapped in an exception
random_data = [random.random() for _ in range(10)]
# Data location inside excel
data_start_loc = [0, 0] # xlsxwriter rquires list, no tuple
data_end_loc = [data_start_loc[0] + len(random_data), 0]
workbook = xlsxwriter.Workbook('file.xlsx')
# Charts are independent of worksheets
chart = workbook.add_chart({'type': 'line'})
chart.set_y_axis({'name': 'Random jiggly bit values'})
chart.set_x_axis({'name': 'Sequential order'})
chart.set_title({'name': 'Insecure randomly jiggly bits'})
worksheet = workbook.add_worksheet()
# A chart requires data to reference data inside excel
worksheet.write_column(*data_start_loc, data=random_data)
# The chart needs to explicitly reference data
chart.add_series({
'values': [worksheet.name] + data_start_loc + data_end_loc,
'name': "Random data",
})
worksheet.insert_chart('B1', chart)
workbook.close() # Write to file
You have 2 options:
If you are on windows, you can use pywin32 (included in ActivePython) library to automate Excel using OLE automation.
from win32com.client import Dispatch
ex = Dispatch("Excel.Application")
# you can use the ex object to invoke Excel methods etc.
If all you want to just generate basic plots etc. you can use matplotlib.
I suggest you to try gnuplot while drawing graph from data files.
If you do decide to use matplotlib, check out my excel to python class PyWorkbooks to get the data. It lets you retrieve data efficiently and easily as numpy arrays (the native datatype for matplotlib).
https://sourceforge.net/projects/pyworkbooks/
#David Gao, I am looking at doing something similar. Currently I am looking at using the raw csv or converting it to json and just dropping it in a folder that is being read by jqplot.jquery plotting and graphing library. Then all I need to do is have the user or myself display the plot in any web browser.