I'm writing a program that, summarized, takes a notepad file and saves it as a excel file.
Right now my program opens up a blank excel file I have created, just "Book1.xls":
xlApp = Dispatch("Excel.Application")
xlApp.Visible=0
xlWb = xlApp.Workbooks.Open(file_path+"/Book1.xls")
workBook = xlApp.ActiveWorkbook
sheet = xlApp.ActiveSheet
and it uses Book1.xls to write into and format as is required, then saves it as another file name using
workBook.SaveAs(new_file_path+'/UpdatedSheet.xls')
I want to know how to simply create a new excel file to write to, then save as a file. Without the need of having Book1.xls already created in a specific directory.
You can create a new workbook using the Add method of the Workbooks object:
>>> import win32com.client as win32
>>> excel = win32.Dispatch("Excel.Application")
>>> workbook = excel.Workbooks.Add()
>>> workbook.SaveAs(new_file_path+'/UpdatedSheet.xls')
Related
I have been testing adding a table to a worksheet using openpyxl, but I get the error below when I try to open it. The file opens, but the formatting isn't correct. After hitting recover, excel reports that there was an issue with the table xml. Is there a workaround/fix for this?
The code I'm using:
import openpyxl
from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
xl_file_name = "new_test.xlsx"
wb = Workbook()
ws = wb.worksheets[0]
ws.title = "Table_Sheet"
headers = ["header1","header2","header3"]
for col in range(1,len(headers)+1):
for row in range(1,5):
if row == 1:
ws.cell(row,col).value = headers[col-1]
else:
ws.cell(row,col).value = str(row)
tbl = Table(displayName="Tbl1",ref="A1:C4")
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tbl.tableStyleInfo = style
ws.add_table(tbl)
wb.save("new_test.xlsx")
Your name for the table is causing the problem. Run the same code with displayName="Tbl" or displayName="Tbl_1" instead, and you'll see it works fine. I'm not 100% sure, but I think the cause of the issue is that the name you give conflicts with the formatting for a possible cell reference of TBL1.
For me the following worked:
Change the Workbook as you wish (only Data no formatting)
Save the Workbook (If you would try to open it here it will display the error message)
Close the Workbook
Open the Workbook again (I think here Excel fixes the issue automatically)
Insert necessary formatting commands
Save the workbook
Close the Workbook
Or, as code:
import openpyxl
workbook = openpyxl.load_workbook(Source_Path)
##your code appending and deleting values - which I think sometimes causes the errors
workbook.save(Destination_Path)
workbook.close
#Now open it again
workbook = openpyxl.load_workbook(Destination_Path)
#Your Code to format
workbook.save(Destination_Path)
workbook.close
Now you should be able to open the Excel file without an error.
I've had the same error message.
I was creating tables with numbers at the start of the name, so I changed that code to add t_ at the beginning, so
table_name = "112MHZ_data"
became
table_name = "t_112MHZ_data"
And that solved it for me.
My code needs to open an Excel file (with formulas) to search for a given value and close this file, will do some calculations and will write the answer in this file.
I can not get Matlab to close the file before it writes the response and this error appears:
Error using xlswrite (line 226)
The file C: \Temp\Data_Home.xlsx is not writable. It might be locked by another process.
File_123 = 'C: \Temp\Data_Home.xlsx';
xlObj = actxserver('Excel.Application'); %Start Excel
wsObj = xlObj.Workbooks.Open(File_123); %Open workbook
Sheet = wsObj.Sheets.Item(3); %Assume we're using the first sheet
Use Quit and delete as mentioned in the example in the documentation of actxserver.
Quit(xlObj);
delete(xlObj);
I want to embedded image , text file into the excel sheet by using python script.
And after that we can check the content of the file by clicking on the object inside the cell.
With below code I am able to insert image into a particular cell (C2).
But my concern is that how to insert an image as an object or text file also an object into a particular cell of the worksheet.
Please check screen shot for reference.
import openpyxl
import time
import datetime
from openpyxl.drawing.image import Image
################### Todays date ###############################
dateToday=datetime.datetime.today()
FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateToday.year))
print (FormatedDate)
#
Read the Workbook
Sigos_DailyHealthCheckReport = r'D:\Script\Monitoring\CheckReport-6-Dec-2017.xlsx'
Load the Workbook
LoadFile = openpyxl.load_workbook(Sigos_DailyHealthCheckReport)
Access first Worksheet of the Workbook
AccessFile = LoadFile.active
################## SHEET 1
To access particular weeksheet with in the workbook.
Sheet2 = LoadFile.get_sheet_by_name('Operational Status Of SITE')
img = Image("D:\Script\Monitoring\Dashboard.png", size=[140,140])
Sheet2['A1'] = 'This is Sid'
Sheet2.add_image(img, 'C2')
LoadFile.save("CheckReport.xlsx")
LoadFile.close()
###### Finally I have develop the script for the above mention question.
###### I am share it so that someone can make use of it if he/she is searching resolution for similar issue.
##pip install pypiwin32 to work with windows operating sysytm and import the module as mentioned below.
import win32com.client
# Creating an object for accessing excel application.
excel_app = win32com.client.Dispatch('Excel.Application')
# Set visible as 1. It is required to perform the desired task.
excel_app.visible = 1
# Open the excel workbook from the desired location in read mode.
workbook = excel_app.Workbooks.Open(r'D:\Script\Monitoring\DailyHealthCheckReport.xlsx')
# Select worksheet by name.
worksheet = workbook.Sheets('Operational Status Of SITE')
# To assign an object for OLEObject(=EMBED("Packager Shell Object","")).
Embedded_object = worksheet.OLEObjects()
# To assign loction of the image file that need to inserted as OBJECT in excel worksheet.
file_loction = "D:\Script\Monitoring\Dashboard.png"
# To add selected file to the excel worksheet. It will add the OBJECT to the A1 cell of the current worksheet.
Embedded_object.Add(ClassType=None, Filename=file_loction, Link=False, DisplayAsIcon=True,Left=3, Top=0, Width=50, Height=50)
# To Copy selected range of cells in the current worksheet.
worksheet.Range('A1:A1').Copy()
# To paste the copied data to a perticular range of cells in currnet worksheet.
worksheet.Paste(Destination=worksheet.Range('C2:C2'))
# To select fist item in the list of object i.e. first object.
obj = Embedded_object.Item(1)
# To delete selected object from the worksheet.
obj.Delete()
when try to open an excel file using VBScript, the values/numbers format gets change, destryoing the values.
For example: "0.0" is changed to "__0.0" (with spaces befores), "9000.0" is turned into "__9000.0" (with spaces befores) and "288" is replaced by "288000".
Some knows how to solve this?
Here is my code to open the file:
Dim ExcelFile
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set ExcelFile = objExcel.Workbooks.Open("File Directory")
I need the data as original (functional) in order to be used by another file.
Couldn't find answers I can understand. So I've decided to ask.
I'm learning Python. And now I'm trying to solve a problem with collecting data from active spreadsheet in one excel file and paste it to another excel file. The first file contains table and a few cells with information to the right of it. I'm trying to fully copy the spreadsheet data.
import openpyxl, os
from openpyxl.cell import get_column_letter
os.chdir('D:\\Python')
wb = openpyxl.load_workbook('auto.xlsx')
ws = wb.active
# Create new workbook and chose active worksheet.
wbNew = openpyxl.Workbook()
wsNew = wbNew.active
# Loop through all cells (rows, then columns) in the first file
# and fill in the second one.
for allObj in ws['A1':get_column_letter(ws.max_column) + str(ws.max_row)]:
for cellObj in allObj:
for allNewObj in wsNew:
for newCellObj in allNewObj:
wsNew[cellObj.coordinate].value = cellObj.value
wbNew.save('example.xlsx')
Finally it works.