I am working on a python prtogram that reads an excel file and based on the information in that file, writes data in the same file
This is my code:
import xlrd
import xlwt
from xlutils import copy
location = "C:\\Users\\adarsh\\Desktop\\Python\\Other\\Blah.xls"
readbook = xlrd.open_workbook(location)
workbook = xlutils.copy(readbook)
sheet = workbook.get_sheet(0)
I get this error when I run my code:
workbook = xlutils.copy(readbook)
AttributeError: module 'xlutils' has no attribute 'copy'
There is an error saying that there is no attribute copy even though online tutorials use that feature
I don't know how to fix this
looks like you haven't imported the right function from the right place. Try this:
from xlutils.copy import copy
Then you can simply call:
copy(readbook)
You imported copy specifically from the module so you shouldn't need the xlutils.copy() it should just be copy()
Related
I'm trying to create a dataframe using a csv file for an assignment however, every time I would run my program it would show me an error that the file couldn't be found. My code is the following:
import pandas as pd
df = pd.read_csv('thefile')
The code returns an error no matter where I place my file. When I checked for the path using the code below:
import os
print(os.getcwd())
It showed me that the path is correct and it is looking inside the folder where my csv file is located but it still returns me the same error.
When reading in files, the 'thefile' must be followed by a .csv extension in the reference, as follows; 'thefile.csv'.
You need to add .csv behind the thefile,
without it, it doesn't know which file to look for it could be thefile.txt, thefile.conf, thefile.csv, thefile.....
So your code should look like this.
import pandas as pd
df = pd.read_csv('thefile.csv')
I have one xls file named template.xls,which has some style and values,i want to insert a value in template.xls.How can i do this?
There's already a thread related to your specific question.
https://stackoverflow.com/a/26958437/8751278
You should utilize this (from abaldwin99):
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
However, you need to install the modules before it works.
It pretty much replaces the very top-left value and sets it to 'A1'.
You, of course, need to change 'names.xls' with your own file's name.
I am trying to get a good method to see if an Excel spreadsheet exists, if it does use that, if not create a new excel file. See code snippet below. The weird thing is every time I run it, it crashed on first attempt. If I run it again, it cruises through. Any ideas why? I am thinking it has something to do with xlrd vs. xlwt, but haven't found a solution yet. All modules are up-to-date.
import pandas as pd
import xlsxwriter
from xlrd import open_workbook
import xlwt
import os.path
fname=r'testmonthlyz.xlsm'
fname2=r'testmonthlyoutput2.xlsx'
#workbook = xlsxwriter.Workbook(fname2)
if os.path.isfile(fname2):
print('old file')
book=open_workbook(fname2)
else:
print('new file')
book=xlwt.Workbook(fname2)
ws = book.add_sheet('Tested')
sheet_names=book.sheet_names()
I believe that the reason that is crashed is since when you are in the else section, you have the line book=xlwt.Workbook(fname2) which means the book type is Workbook which has no attribute called sheet_names().
When you are using book = open_workbook(fname2) inside the if, book type is Book which does have sheet_names() attribute.
my solution to this, even though is's not the best way, but I think it will solve the issue you are dealing with..
change the following lines
import pandas as pd
import xlsxwriter
from xlrd import open_workbook
import xlwt
import os.path
fname=r'testmonthlyz.xlsm'
fname2=r'testmonthlyoutput2.xlsx'
workbook = xlsxwriter.Workbook(fname2)
if os.path.isfile(fname2):
print('old file')
book=open_workbook(fname2)
else:
print('new file')
workbook2=xlwt.Workbook(fname2)
ws = workbook2.add_sheet('Tested')
workbook2.save(fname2)
book = open_workbook(fname2)
sheet_names=book.sheet_names()
I have a simple excel file:
A1 = 200
A2 = 300
A3 = =SUM(A1:A2)
this file works in excel and shows proper value for SUM, but while using openpyxl module for python I cannot get value in data_only=True mode
Python code from shell:
wb = openpyxl.load_workbook('writeFormula.xlsx', data_only = True)
sheet = wb.active
sheet['A3']
<Cell Sheet.A3> # python response
print(sheet['A3'].value)
None # python response
while:
wb2 = openpyxl.load_workbook('writeFormula.xlsx')
sheet2 = wb2.active
sheet2['A3'].value
'=SUM(A1:A2)' # python response
Any suggestions what am I doing wrong?
It depends upon the provenance of the file. data_only=True depends upon the value of the formula being cached by an application like Excel. If, however, the file was created by openpyxl or a similar library, then it's probable that the formula was never evaluated and, thus, no cached value is available and openpyxl will report None as the value.
I have replicated the issue with Openpyxl and Python.
I am currently using openpyxl version 2.6.3 and Python 3.7.4. Also I am assuming that you are trying to complete an exercise from ATBSWP by Al Sweigart.
I tried and tested Charlie Clark's answer, considering that Excel may indeed cache values. I opened the spreadsheet in Excel, copied and pasted the formula into the same exact cell, and finally saved the workbook. Upon reopening the workbook in Python with Openpyxl with the data_only=True option, and reading the value of this cell, I saw the proper value, 500, instead of the wrong value, the None type.
I hope this helps.
I had the same issue. This may not be the most elegant solution, but this is what worked for me:
import xlwings
from openpyxl import load_workbook
excel_app = xlwings.App(visible=False)
excel_book = excel_app.books.open('writeFormula.xlsx')
excel_book.save()
excel_book.close()
excel_app.quit()
workbook = load_workbook(filename='writeFormula.xlsx', data_only=True)
I have suggestion to this problem. Convert xlsx file to csv :).
You will still have the original xlsx file. The conversion is done by libreoffice (it is that subprocess.call() line).You can use also Pandas for this as a more pythonic way.
from subprocess import call
from openpyxl import load_workbook
from csv import reader
filename="test"
wb = load_workbook(filename+".xlsx")
spread_range = wb['Sheet1']
#what ever function there is in A1 cell to be evaluated
print(spread_range.cell(row=1,column=1).value)
wb.close()
#this line can be done with subprocess or os.system()
#libreoffice --headless --convert-to csv $filename --outdir $outdir
call("libreoffice --headless --convert-to csv "+filename+".xlsx", shell=True)
with open(filename+".csv", newline='') as f:
reader = reader(f)
data = list(reader)
print(data[0][0])
or
# importing pandas as pd
import pandas as pd
# read an excel file and convert
# into a dataframe object
df = pd.DataFrame(pd.read_excel("Test.xlsx"))
# show the dataframe
df
I hope this helps somebody :-)
Yes, #Beno is right. If you want to edit the file without touching it, you can make a little "robot" that edits your excel file.
WARNING: This is a recursive way to edit the excel file. These libraries are depend on your machine, make sure you set time.sleep properly before continuing the rest of the code.
For instance, I use time.sleep, subprocess.Popen, and pywinauto.keyboard.send_keys, just add random character to any cell that you set, then save it. Then the data_only=True is working perfectly.
for more info about pywinauto.keyboard: pywinauto.keyboard
# import these stuff
import subprocess
from pywinauto.keyboard import send_keys
import time
import pygetwindow as gw
import pywinauto
excel_path = r"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE"
excel_file_path = r"D:\test.xlsx"
def focus_to_window(window_title=None): # function to focus to window. https://stackoverflow.com/a/65623513/8903813
window = gw.getWindowsWithTitle(window_title)[0]
if not window.isActive:
pywinauto.application.Application().connect(handle=window._hWnd).top_window().set_focus()
subprocess.Popen([excel_path, excel_file_path])
time.sleep(1.5) # wait excel to open. Depends on your machine, set it propoerly
focus_to_window("Excel") # focus to that opened file
send_keys('%{F3}') # excel's name box | ALT+F3
send_keys('AA1{ENTER}') # whatever cell do you want to insert somthing | Type 'AA1' then press Enter
send_keys('Stackoverflow.com') # put whatever you want | Type 'Stackoverflow.com'
send_keys('^s') # save | CTRL+S
send_keys('%{F4}') # exit | ALT+F4
print("Done")
Sorry for my bad english.
As others already mentioned, Openpyxl only reads cashed formula value in data_only mode. I have used PyWin32 to open and save each XLSX file before it's processed by Openpyxl to read the formulas result value. This works for me well, as I don't process large files. This solution will work only if you have MS Excel installed on your PC.
import os
import win32com.client
from openpyxl import load_workbook
# Opening and saving XLSX file, so results for each stored formula can be evaluated and cashed so OpenPyXL can read them.
excel_file = os.path.join(path, file)
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False # disabling prompts to overwrite existing file
excel.Workbooks.Open(excel_file )
excel.ActiveWorkbook.SaveAs(excel_file, FileFormat=51, ConflictResolution=2)
excel.DisplayAlerts = True # enabling prompts
excel.ActiveWorkbook.Close()
wb = load_workbook(excel_file)
# read your formula values with openpyxl and do other stuff here
I ran into the same issue. After reading through this thread I managed to fix it by simply opening the excel file, making a change then saving the file again. What a weird issue.
For a process I am maintaining, I have a script that creates a csv file and then I copy the csv file into an Excel workbook with buttons that activate macros. This process works just fine.
I am trying to improve that process by writing a script that builds the workbook directly, thus eliminating a step. I thought the best way to do that was to create a template workbook where the first worksheet has the macro button. Then I would simply copy the template workbook, add in my data and save the new workbook under a new custom name. My test code is below:
import csv, os, sys, xlrd, xlwt, xlutils, shutil
from copy import deepcopy
from xlutils import save
from xlutils.copy import copy
templatefile = 'N:\Tools\Scripts-DEV\Testing_Template.xls'
Destfile = 'N:\Tools\Scripts-DEV\Testing_Dest.xls'
shutil.copy(templatefile,Destfile)
# Works fine up to here.
# If you look at the new file, it has the button that is in the template file.
rb = xlrd.open_workbook(Destfile)
rs = rb.sheet_by_index(0)
wb = copy(rb)
wb.get_sheet(0).write(3, 0, 'Due Date')
wb.get_sheet(0).write(3, 1, 'Name')
wb.get_sheet(0).write(3, 3, 'Category')
wb.get_sheet(0).write(3, 4, 'Number')
wb.save(Destfile)
Here is where the problem shows up. After you save, the macro button disappears. I've been looking for a couple days but I haven't (yet) found a way to save the updated Excel file without losing the macro button.
I've been looking at Preserving styles using python's xlrd,xlwt, and xlutils.copy but that doesn't quite meet my needs as I'm trying to preserve a button, not a style.
Does anyone know a way to do this?
I'm about to start looking at alternatives to xlutils, xlrd and xlwt as well, but I thought I'd ask here first.
From you comment part C:\Python27\ I deduce that you are on Windows. In that case you are probably better off with using pywin32 and a template .xls or .xlsm file.
Open the file using os.startfile(filename) then connect using workbook = win32com.client.GetObject(filename). The resulting workbook can be filled with the data and written to a new file with `workbook.SaveAs(newfilename).
Anything you do not touch explicitly is preserved. Excel is, of course, somewhat better at that than xlrd, xlwt and xlutils.