I would like to draw a line between the centers of two ( non-adjacent ) cells in an Excel work sheet using openpyxl.
Using openpyxl I have created a fairly large lookup table. Many of the points in the lookup table are interpolated from a hand full of known points.
I would like to draw lines between the cells that were created using the known points. These lines would sort of circle the areas that are interpolated.
Expected Result:
(This is the actual Excel generated spread sheet, The lines were added by hand in Excel. I want to automate the line drawing. )
In this case the white cells are known data points. Green(ish) cells are inside of the bounding trianges. Redish-Blueish are outside.
All of data on this sheet was populated via a new sheet using openpyxl.
The openpyxl documention hints that this is possible but I do not understand how.
Something along the lines of:
ws.Line['A1':'P17].style['heavy','black']
I think is what I am looking for.
[A bit more data ]
Using Excel and win32com I can automate drawing these lines.
line = ws.Shapes.Addline(3,4,70,80).Line
However do to other limitations in Excel I have to create this offline using openpyxl. Other_Limitations
So to re-phrase my question:
Can openpyxl even draw lines?
I am beginning to think that I will have to create the spreadsheet with openpyxl then open the newly created workbook with Excel and draw the lines with Excel.
I really don't think Excel is suitable for this. The drawing subsystem uses a completely different coordinate system to the worksheet itself. Thus, although it is possible to "anchor" a drawing between two cells, the proportions will be extremely hard to calculate.
I'm sure matplotlib, seaborn or other graphics libraries have tools more suitable for this job.
So my original Question was if this can be done with Openpyxl.
That question still stands.
However here is my solution to draw lines with win32com / Python in Excel directly.
This is not ideal for my situation but it works.
def Drawline(Sheet,Start,End):
StartCell = Sheet.Cells(Start[0],Start[1])
StartAdjacent = Sheet.Cells(Start[0]+1,Start[1]+1)
EndCell = Sheet.Cells(End[0],End[1])
EndAdjacent = Sheet.Cells(End[0]+1,End[1]+1)
Y1 = ( StartCell.Top + StartAdjacent.Top ) / 2
X1 = ( StartCell.Left + StartAdjacent.Left ) / 2
Y2 = ( EndCell.Top + EndAdjacent.Top ) / 2
X2 = ( EndCell.Left + EndAdjacent.Left ) / 2
Sheet.Shapes.AddLine(X1,Y1,X2,Y2)
This will draw a line from the center of Start to the center of End on Sheet.
Related
I am using the PlyFile library (https://pypi.org/project/plyfile) in Python.
I used vertex = plydata['vertex'] to generate a list of vertex co-ordinates. The datatype is as follows -
PlyElement('vertex', (PlyProperty('x', 'float'), PlyProperty('y', 'float'), PlyProperty('z', 'float')), count=2500086, comments=[])
After that I generated a list of all the x-axis values and put them into a numpy array and performed some operations on them. Then I replaced the original x-axis values in plydata['vertex'] with these new ones.
Now I want to write these values into a .ply file and create a new mesh. How would I go about it? I tried going through the docs but the code is quite messy.
Any insights would help, Thanks!
Saving a .ply file:
ply_data: PlyData
ply_data.text = True # for asci format
ply_data.write(path)
I have csv data containing latitude and longitude. I wish to create a 'heatmap' whereby some placemarks are certain colours based on values corresponding to each lat+long point in the csv.
import simplekml
import csv
kml = simplekml.Kml()
kml.document.name = "Test"
with open('final.csv', 'rb') as f:
reader = csv.reader(f)
first_row = reader.next() # removes csv header string
long = col[1]
lat = col[2]
for col in reader:
pnt = kml.newpoint()
pnt.name = 'test-name'
pnt.coords = [(long, lat, 10000)]
pnt.description = col[0] # timestamp data
pnt.style.labelstyle.color = 'ff0000ff'
kml.save("test.kml")
This script creates a kml file that on inspection with google earth presents the data points but I want some kind of graphical input too.
It doesn't seem like simplekml package supports such things.. Any advice on what python package is best to get a 'heatmap' or something along those lines? Or even I can add kml elements directly in the script but the documentation it seems is rather limited for the solutions I require.
Thanks
Sounds like you're looking to create a "thematic map", not a "heatmap".
Looks like you're using pnt.style.labelstyle.color = ... to add colors. LabelStyle refers to the text labels associated with icons, not the icons themselves. What you probably want is to refer to differently colored icons based on your attribute values. You should be able to do that with: pnt.style.iconstyle.icon.href = .... Either specify a colored icon image, or use a white image and apply a color with style.iconstyle.color = ....
Best practice for KML would be to set up several shared styles, one for each icon color, and then apply the relevant style to each point with pnt.style = ....
Implementation details are in the simplekml documentation.
Years ago for a masters project my friend took a bunch of data from an excel sheet and used them in a powerpoint graph. He told me he made the graph in excel then copied it into powerpoint. Now, when I hover over the graph I see the points associated to where my mouse hovers. My friend lost the original excel sheet and is asking me to help pull the data from the powerpoint graph and put it in an excel sheet.
How would I go about doing this? If theres away to get the points into a json file I can do the rest. I just know nothing about powerpoint graphs.
Right click the chart, choose Edit Data.
If it's an embedded chart, the chart and its workbook will open in Excel.
From there you can File | Save As and save your new Excel file.
years ago I used a program called DataThief - takes a scan of a graph and produces x's and y's according to how many you ask for for resolution.
Amazingly it is still around DataThief III and you can find it here:
http://datathief.org
I'm not sure what this has to do with Python. Also, I'll bet anything the data is already coming from Excel and it's converted into a PowerPoint slide. I doubt it's working the way you described it. Check out the Macro below and see if it helps you with your project.
Sub Open_PowerPoint_Presentation()
Dim objPPT As Object, _
PPTPrez As PowerPoint.Presentation, _
pSlide As PowerPoint.Slide
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True
Set PPTPrez = objPPT.Presentations.Open("C:\PPT_Deck.pptx")
Set pSlide = PPTPrez.Slides(5)
If pSlide.Shapes.Count <> 0 Then
'Table
ActiveWorkbook.Sheets("Sheet1").Range("Named Range").Copy
pSlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
'OR
ActiveWorkbook.Sheets("Sheet1").Range("Named Range").CopyPicture
pSlide.Shapes.Paste
'Charts
ActiveWorkbook.Sheets("Graph1").ActiveChart.ChartArea.Copy
pSlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
'OR
ActiveWorkbook.Sheets("Graph1").ActiveChart.ChartArea.CopyPicture
pSlide.Shapes.Paste
Else
MsgBox "There is no shape in this Slide (" & pSlide.SlideIndex & ")." & vbCrLf & "Please use a slide with at least one shape, not a blank slide", vbCritical + vbOKOnly
End If
End Sub
I have a stack of CT-scan images. After processing (one image from those stack) CT-scan image using Matlab, I saved XY coordinates for each different boundary region in different Excel sheets as follows:
I = imread('myCTscan.jpeg');
BW = im2bw(I);
[coords, labeledImg] = bwboundaries(BW, 4, 'holes');
sheet = 1;
for n=1:length(coords);
xlswrite('fig.xlsx',coords{n,1},sheet,'A1');
sheet = sheet+1;
end
The next step is then to import this set of coordinates and plot it into Abaqus CAE Sketch for finite element analysis.
I figure out that my workflow is something like this:
Import Excel workbook
For each sheet in workbook:
2.1. For each row: read both column to get xy coordinates (each row has two column, x and y coordinate)
2.2. Put each xy coordinates inside a list
2.3. From list, sketch using spline method
Repeat step 2 for other sheets within the workbook
I searched for a while and found something like this:
from abaqus import *
lines= open('fig.xlsx', 'r').readlines()
pointList= []
for line in lines:
pointList.append(eval('(%s)' %line.strip()))
s1= mdb.models['Model-1'].ConstrainedSketch(name='mySketch', sheetSize=500.0)
s1.Spline(points= pointList)
But this only read XY coordinates from only one sheet and I'm stuck at step 3 above. Thus my problem is that how to read these coordinates in different sheets using Abaqus/Python (Abaqus 6.14, Python 2.7) script?
I'm new to Python programming, I can read and understand the syntax but can't write very well (I'm still struggling on how to import Python module in Abaqus). Manually type each coordinates (like in Abaqus' modelAExample.py tutorial) is practically impossible since each of my CT-scan image can have 100++ of boundary regions and 10k++ points.
I'm using:
Windows 7 x64
Abaqus 6.14 (with built in Python 2.7)
Excel 2013
Matlab 2016a with Image Processing Toolbox
You are attempting to read excel files as comma separated files. CSV files by definition can not have more than one tab. Your read command is interpreting the file as a csv and not allowing you to iterate over the tabs in your file (though it begs the question how your file is opening properly in the first place as you are saving an xlsx and reading a csv).
There are numerous python libraries that will parse and process XLS/XLSX files.
Take a look at pyxl and use it to read your file in.
You would likely use something like
from openpyxl import Workbook
(some commands to open the workbook)
listofnames=wb.sheetnames
for k in listofnames:
ws=wb.worksheets(k)
and then input your remaining commands.
I am trying to scrape a .xlsx excel file for chart objects and export them as images. The only similar stackoverflow question I found was this one which attempts to do the same thing. The script, however, does not seem to work (even when I correct the syntax/methods).
I am willing to get this running in either Python 2.7.9 or 3.4.0. as I have both versions running on my computer.
Here is the code I am working with:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'C:\Users\Emilyn\Desktop\chartTest.xlsx')
excel.Visible = True
wb.Sheets("Sheet1").Select()
wbSheetOne = wb.Sheets(1)
wb.DisplayAlerts = False
i = 0
for chart in wbSheetOne.ChartObjects():
print(chart.Name)
chart.CopyPicture()
excel.ActiveWorkbook.Sheets.Add(After =excel.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)
temp_sheet = wb.ActiveSheet
cht = wb.ActiveSheet.ChartObjects().Add(0,0,800,600)
cht.Chart.Export("chart" + str(i) + ".png")
i = i+1
excel.ActiveWorkbook.close
wb.DisplayAlerts = True
This opens my excel file, generates three .png images in my documents folder, and creates three new worksheets for the images, but the images are all blank.I am not sure what I can do to get the chart objects in my excel file to correctly copy to these newly created images.
Any help I could get on this would be greatly appreciated as there seems to be no in depth documentation on pywin/win32com anywhere.
I've been searching the internet like mad and trying to get this to work for a day or two now... It's hard to get something to work when you don't know all of the methods available, or even what some of the methods do.
(Yes, I have read all the "read me" files that came with the library and read what they offered on their website as well.)
I already figured out what to do but I suppose I'll post it for future users.
for index in range(1, count + 1):
currentChart = wbSheet.ChartObjects(index)
currentChart.Copy
currentChart.Chart.Export("chart" + str(index) + ".png")
I used a count to do a for loop, this way you dynamically read the amount of chart objects in an excel file.
Also, the reason I started the range at 1 is because VB in excel starts index of objects at 1, not zero.
You copy an existing chart as a picture, but don't do anything with it.
You insert a worksheet, without adding any data, then you embed a chart in that worksheet, which must be blank since there's no data to display, then export the blank chart as a png file.