I am fairly new to programming, and even newer to Tkinter.
I am setting up a GUI that works with an SQL Server to allow front end users to retrieve, update, and delete certain information.
Currently I have everything communicating and working correctly, but I have a function that exports a list of the results into an excel file using Pandas. The export works fine, but it has the static name and directory I give it inside the Pandas to_excel method.
I want to use a Tkinter asksaveasfilename dialog to allow the user to name and choose the files export location, but I can't seem figure out how this works with this dialogue box (if it is even possible). Is there an option inside the dialog boxes code where I specify what information I want to save?
def exportFunc():
pd.DataFrame(data).to_excel("TestList.xlsx", header=False, index = True)
filedialog.asksaveasfilename(initialdir = "/", title = 'Save File', filetypes = ("Excel File", "*.xlsx"))
pass
My code doesn't produce any errors, just simply saves nothing with the dialogue box with everything I try. Right now I have the file dialog commented out in my actual code, but if someone could direct me towards a possible solution, I would be grateful!
10 months ago this was posted, but I hope this answer can help a fellow novice googling around for this answer as well.
How I solved this was noticing the asksaveasfile function outputs a value that contains the user specified file path and file name. For example:
< closed file u'E:Filepath/AnotherPath/work2.xlsx', mode 'w' at 2119x6710 >
I then used regex and the replace method to strip away all values surrounding the filepath, which once finished, the to_excel function would see as a hardcode.
Hope this helps someone out there!
out = tkFileDialog.asksaveasfile(mode='w', defaultextension=".xlsx")
out.close()
restr = str(out)
RegexPrep = restr.replace("'w'", '')
outRegex = re.findall(r"'(.*?)'", RegexPrep)
ToExcelRegex = str(outRegex)
MorePrep = ToExcelRegex.replace("[",'')
MorePrep = MorePrep.replace("]",'')
MorePrep = MorePrep.replace("'",'')
Final = MorePrep.strip()
find.to_excel(Final, index=False)
Asksavasafile returns a file object, so we can use that to save the df.
from tkinter import filedialog, Tk
import pandas as pd
df = pd.DataFrame(
{"Test": range(20)}
)
root = Tk() # this is to close the dialogue box later
try:
# with block automatically closes file
with filedialog.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
df.to_excel(file.name)
except AttributeError:
# if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
print("The user cancelled save")
root.destroy() # close the dialogue box
Related
Hi I write program that will take many csv filles make three new structure for them.
After that program concat the same csv files in one structure depends of its name.
All this i done alredy but i need to save this three new files. I did it by using tkinter and it works, code look like this:
list_of_df = [completeDR,completeDS,completeDD,completeKL]
for i in list_of_df:
if not i.empty:
root = Tk() # this is to close the dialogue box later
try:
# with block automatically closes file
with filedialog.asksaveasfile(mode='w', defaultextension=".csv") as file:
i.to_csv(file.name, index = False)
except AttributeError:
# if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
print("The user cancelled save")
root.destroy() # close the dialogue box
This solutions work rly good but I have one problem. When I save files I need to named it but i dont know which one i save in this moment. I need solution that let me save files exacly in the same place where application will be run. Second option is to change name of title in tkinter winodw. If title will say me what i save right now there will be no problem anymore. Anyone have some ideas ? Thanks for help.
I am currently working on an application that will convert a messy text file full of data into an organized CSV. It currently works well but when I convert the text file to csv I want to be able to select a text file with any name. The way my code is currently written, I have to name the file "file.txt". How do I go about this?
Here is my code. I can send the whole script if necessary. Just to note this is a function that is linked to a tkinter button. Thanks in advance.
def convert():
df = pd.read_csv("file.txt",delimiter=';')
df.to_csv('Cognex_Data.csv')
Try defining your function as follow:
def convert(input_filename, output_filename='Cognex_Data.csv'):
df = pd.read_csv(input_filename, delimiter=';')
df.to_csv(output_filename)
And for instance use it as follow:
filename = input("Enter filename: ")
convert(filename, "Cognex_Data.csv")
You can also put "Cognex_Data.csv" as a default value for the output_filename argument in the convert function definition (as done above).
And finally you can use any way you like to get the filename (for instance tkinter.filedialog as suggested by matszwecja).
I haven't worked with tkinter, but PySimplyGUI, which to my knowledge is built on tkinter so you should have the possibility to extract the variables that correspond to the name of the file selected by the user. That's what I'm doing using PySimpleGUIon a similar problem.
Then, extract the file name selected by the user through the prompt and pass it as an argument to your function:
def convert(file):
df = pd.read_csv("{}.txt".format(file), delimiter=';')
df.to_csv('Cognex_Data.csv')
I'm trying to create a Python script (I'm using Python 3.7.3 with UTF-8 encoding on Windows 10 64-bit with Microsoft Office 365) that exports user selected worksheets to PDF, after the user has selected the Excel-files.
The Excel-files contain a lot of different settings for page setup and each worksheet in each Excel-file has a different page setup.
The task is therefore that I need to read all current variables regarding page setup to be able to assign them to the related variables for export.
The problem is when I'm trying to get Excel to return the current print area of the worksheet, which I can't figure out.
As far as I understand I need to be able to read the current print area, to be able to set it for the export.
The Excel-files are a mixture of ".xlxs" and ".xlsm".
I've tried using all kind of different methods from the Excel VBA documentation, but nothing has worked so far e.g. by adding ".Range" and ".Address" etc.
I've also tried the ".UsedRange", but there is no significant difference in the cells that I can search for and I can't format them in a specific way so I can't use this.
I've also tried using the "IgnorePrintAreas = False" variable in the "ExportAsFixedFormat"-function, but that didn't work either.
#This is some of the script.
#I've left out irrelevant parts (dialogboxes etc.) just to make it shorter
#Import pywin32 and open Excel and selected workbook.
import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = False
wb = excel.Workbooks.Open(wb_path)
#Select the 1st worksheet in the workbook
#This is just used for testing
wb.Sheets([1]).Select()
#This is the line I can't get to work
ps_prar = wb.ActiveSheet.PageSetup.PrintArea
#This is just used to test if I get the print area
print(ps_prar)
#This is exporting the selected worksheet to PDF
wb.Sheets([1]).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path, Quality = 0, IncludeDocProperties = True, IgnorePrintAreas = False, OpenAfterPublish = True)
#This closes the workbook and the Excel-file (although Excel sometimes still exists in Task Manager
wb.Close()
wb = None
excel.Quit()
excel = None
If I leave the code as above and try and open a test Excel-file (.xlxs) with a small PrintArea (A1:H8) the print function just gives me a blank line.
If I add something to .PrintArea (as mentioned above) I get 1 of 2 errors:
"TypeError: 'str' object is not callable".
or
"ps_prar = wb.ActiveSheet.PageSetup.PrintArea.Range
AttributeError: 'str' object has no attribute 'Range'"
I'm hoping someone can help me in this matter - thanks, in advance.
try
wb = excel.Workbooks.OpenXML(wb_path)
insead of
wb = excel.Workbooks.Open(wb_path)
My problem was with a german version of ms-office. It works now. Check here https://social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff-5c0d83166e73/excel-api-interne-namen?forum=officede
I made a vbscript to open an excel doc, then runs a python program that pulls data from the documents tables and prints it to a text file. The script is supposed to wait until the python program is done creating the text doc then close the excel doc, but for whatever reason my python program closes before it even has a chance to make that text doc.
I even changed the python code to just print a simple 'Hello World' into a new text document in case pulling data from excel was causing problems but the text document still wasn't created.
This is the script that i'm running:
Set xl = CreateObject("Excel.application")
xl.Application.Workbooks.Open "C:\Users\V\Documents\_PROGRAMS_\TEST.xlsx"
xl.Application.Visible = True
Dim oshell
Set oshell = WScript.CreateObject("WScript.Shell")
oshell.CurrentDirectory = "C:\Users\V\Documents\_PROGRAMS_\"
windowStyle = 1
waitUntilFinished = True
oshell.run "python table.py", windowStyle, waitUntilFinished
xl.Application.Quit
I don't think adding the python program is important since that isn't really the problem. Although I will say that I tried putting a delay in the python program to see if that would change anything (it didn't).
I though adding the two extra arguments to .run would make it wait until the process is finished but I guess I must be missing something?
I'm just starting to learn how to use vbscript so any explanations of code would be welcomed!
Thanks!
EDIT: So after more testing it seems that it does have something to do with accessing the excel document, as just printing 'Hello World' to a file did actually work and the file was created (I made it in the wrong directory by accident so I was looking in the wrong place). But trying it with the data from the excel document no file is created, the program just ends
So here's the python code I wrote:
#!/usr/bin/python27
import pandas as pd
table = pd.read_excel("TEST.xlsx") #Get excel doc
file = open("text.txt", "w") #Open new file
file.write(table.columns.values) #Print out column headers
file.write("Hello!")
file.close()
My task is simple, I want to open a word template, add some text and tables to the word doc, save it as PDF and exit out of word.
Because of the nature of the beast I don't want to save the document in word format, and for it all to work the PDF needs to be generated with no user interaction with word.
There may be better ways of solving this task, but they are the parameters by which I am constrained. The other constraint is that it needs to run with python 2.4...
My starting point was Mark Hammonds easyword.py sample script, and I have got it to do most of what I want, but, there are two issues that I just cannot seem to figure out, and are probably related.
When I run the test() function I get my output PDF and Word docs generated correctly, but
1) I don't seem to be able to 'close' the word session/document
2) I end up with an annoying dialog box asking me if I want to save changes.
The dialog box is a deal breaker.
In my Quit function Close() doesn't appear to be recognised, and none of the tools I've got are giving me any methods at all for 'self.wordapp', although the self.wordapp.Quit() does appear to work (doesn't cause a crash).
I've spent hours searching for an answer to this, both on the internet and looking at similar code for Excel (formatting is why I can't using Excel) to no avail. Does anyone have any ideas?
The relevant sections of my test code are below:
import win32com.client
MYDIR = 'somevalidpath'
class WordWrap:
''' Wrapper around Word documents to make them easy to build.
Has variables for the Applications, Document and Selection;
most methods add things at the end of the document
'''
def __init__(self, templatefile=None):
self.wordApp = win32com.client.gencache.EnsureDispatch('Word.Application')
if templatefile == None:
self.wordDoc = self.wordApp.Documents.Add()
else:
self.wordDoc = self.wordApp.Documents.Add(Template=templatefile)
#set up the selection
self.wordDoc.Range(0,0).Select()
self.wordSel = self.wordApp.Selection
def Quit(self):
self.wordApp.Close(SaveChanges=1)
self.wordApp.Quit()
def test():
'''
Test function for class
'''
outfilename = MYDIR + '\\pythonics_mgt_accounts.doc'
w = WordWrap(MYDIR + '\\pythonics.dot')
#w.show()
w.addStyledPara('Accounts for April', 'Title')
#first some text
w.addStyledPara("Chairman's Introduction", 'Heading 1')
w.addStyledPara(randomText(), 'Normal')
# now a table sections
w.addStyledPara("Sales Figures for Year To Date", 'Heading 1')
data = randomData()
w.addTable(data, 37) # style wdTableStyleProfessional
w.addText('\n\n')
# finally a chart, on the first page of a ready-made spreadsheet
w.addStyledPara("Cash Flow Projections", 'Heading 1')
w.addInlineExcelChart(MYDIR + '\\wordchart.xls', 'Cash Flow Forecast')
w.saveAs(outfilename)
print 'saved in', outfilename
# save as PDF, saveAs handles the file conversion, based on the file extension
# the file is not just being renamed and saved
new_name = outfilename.replace(".doc", r".pdf")
w.saveAs(new_name)
print 'saved in', new_name
w.Quit()
Doh, it would have helped if I'd tried to close the document, and not the application. Code should read self.wordDoc.Close()