Python: Modifying Excel files while maintaing formatting - python

Is there any way to modify a few cells in an existing Excel file without losing formatting, and without using xlutils?
I have access to xlwt, and xlrd, but not xlutils.
Thank you!

Although its use is deprecated nowadays, you can use from win32com.client module which contains "dispatch". It preserves formatting.
Example :
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible=1
book = xlApp.Workbooks.Open("FileName")
sheet1 = book.Worksheets(1)
sheet1.Cells(1,1).Value="ABC"

Related

How to convert Excel SpreadsheetML to .xlsx using python

I'm new to python, so i have this XML file which i can open pretty easily using Excel,
this is XML file
andi want to convert it to .xlsx or any compatible format to be able to use openpyxl module to it so that i can read it easily, is there any way to do this on python? Any advice would be appreciated thankyou.
I had the same problem. This answer helped me
Attempting to Parse an XLS (XML) File Using Python
You may save your Excel styled XML as xlsx with Workbook.SaveAs method using win32com (only for Windows users) and read in with pandas.read_excel
import win32com.client
import pandas as pd
original_file = "Your_downloaded_file.xml"
output = "Your_converted_file.xlsx"
xlApp = win32com.client.Dispatch("Excel.Application")
xlWbk = xlApp.Workbooks.Open(original_file)
xlWbk.SaveAs(output, 51)
xlWbk.Close(True)
xlApp.Quit()
output_df = pd.read_excel(output)
print(output_df.columns.ravel())

Is there a way to protect workbooks using openpyxl or xlswriter?

I'm trying to automate Excel reports, and I'd prefer users didn't try to rename or reorder the worksheets. While I've had no problems protecting individual cells using xlsxwriter, I've failed to see an option to protect the workbook itself. I'm looking to openpyxl, but the tutorial does not seem to have any effect.
Edit: I'm now using this block of code, but does neither produce an error or protect my workbooks.
from openpyxl import load_workbook
from openpyxl.workbook.protection import WorkbookProtection
workbook = load_workbook(filepath, read_only=False, keep_vba=True)
workbook.security = WorkbookProtection(workbookPassword = 'secret-password', lockStructure = True)
workbook.save(filepath)
By the way, I am dealing with .xlsm files. If there are any solutions or points that I've missed, please let me know.
From this code:
from openpyxl.workbook.protection import WorkbookProtection
myWorkbook.security = WorkbookProtection(workBookPassword = 'super-secret-password', lockStructure = True)
myWorkbook.save(filepath)
Change:
WorkbookProtection(workBookPassword = 'super-secret-password', lockStructure = True)
to:
WorkbookProtection(workbookPassword = 'super-secret-password', lockStructure = True)
workBookPassword should be workbookPassword
Tested on Python32 3.8 and OpenPyXL version 3.0.2
Xlsxwriter has the option to protect the workbook with the command worksheet.protect() (have a look at the documentation: https://xlsxwriter.readthedocs.io/worksheet.html )
However take into consideration this:
Worksheet level passwords in Excel offer very weak protection. They do
not encrypt your data and are very easy to deactivate. Full workbook
encryption is not supported by XlsxWriter since it requires a
completely different file format and would take several man months to
implement.
Try using xlwings
import xlwings as xw
wb = xw.Book(r'<path_to_.xlsx file>')
wb.save(password='<your_password>', path=r'<path_to_save_.xlsx file>')

Write data into existing excel file and making summary table

I have to write some data into existing xls file.(i should say that im working on unix and couldnt use windows)
I prefer work with python and have tried some libraries like xlwt, openpyxl, xlutils.
Its not working, cause there is some filter in my xls file. After rewriting this file filter is dissapearing. But i still need this filter.
Could some one tell me about options that i have.
help, please!
Example:
from xlutils.copy import copy
from xlrd import open_workbook
from xlwt import easyxf
start_row=0
rb=open_workbook('file.xls')
r_sheet=rb.sheet_by_index(1)
wb=copy(rb)
w_sheet=wb.get_sheet(1)
for row_index in range(start_row, r_sheet.nrows):
row=r_sheet.row_values(row_index)
call_index=0
for c_el in row:
value=r_sheet.cell(row_index, call_index).value
w_sheet.write(row_index, call_index, value)
call_index+=1
wb.save('file.out.xls');
I also tried:
import xlrd
from openpyxl import Workbook
import unicodedata
rb=xlrd.open_workbook('file.xls')
sheet=rb.sheet_by_index(0)
wb=Workbook()
ws1=wb.create_sheet("Results", 0)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws1.append(arr)
ws2=wb.create_sheet("Common", 1)
sheet=rb.sheet_by_index(1)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws2.append(arr)
ws2.auto_filter.ref=["A1:A15", "B1:B15"]
#ws['A1']=42
#ws.append([1,2,3])
wb.save('sample.xls')
The problem is still exist. Ok, ill try to find machine running on windows, but i have to admit something else:
There is some rows like this:
enter image description here
Ive understood what i was doing wrong, but i still need help.
First of all, i have one sheet that contains some values
Second sheet contains summary table!!!
If i try to copy this worksheet it did wrong.
So, the question is : how could i make summary table from first sheet?
Suppose your existing excel file has two columns (date and number).
This is how you will append additional rows using openpyxl.
import openpyxl
import datetime
wb = openpyxl.load_workbook('existing_data_file.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
a = sheet.get_highest_row()
sheet.cell(row=a,column=0).value=datetime.date.today()
sheet.cell(row=a,column=1).value=30378
wb.save('existing_data_file.xlsx')
If you are on Windows, I would suggest you take a look at using the win32com.client approach. This allows you to interact with your spreadsheet using Excel itself. This will ensure that any existing filters, images, tables, macros etc should be preserved.
The following example opens an XLS file adds one entry and saves the whole workbook as a different XLS formatted file:
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'input.xls')
ws = wb.Worksheets(1)
# Write a value at A1
ws.Range("A1").Value = "Hello World"
excel.DisplayAlerts = False # Allow file overwrite
wb.SaveAs(r'sample.xls', FileFormat=56)
excel.Application.Quit()
Note, make sure you add full paths to your input and output files.

Python append xls file using only xlwt/xlrd

I am having problems appending issues appending data to an xls file.
Long story short, I am using a program to get some data from something and writing it in an xls file.
If I run the script 10 times, I would like the results to be appended to the same xls file.
My problem is that I am forced to use Python 3.4 and xlutils is not supported, so I cannot use the copy function.
I just have to use xlwt / xlrd. Note, the file cannot be a xlsx.
Is there any way i can do this?
I would look into using openpyxl, which is supported by Python 3.4. An example of appending to a file can be found https://openpyxl.readthedocs.org/en/default/. Please also see: How to append to an existing excel sheet with XLWT in Python. Here is an example that will do it. Assuming you have an Excel sheet called sample.xlsx:
from openpyxl import Workbook, load_workbook
# grab the active worksheet
wb = load_workbook("sample.xlsx")
ws = wb.active
ws.append([3])
# Save the file
wb.save("sample.xlsx")

editing existing excel workbook using xlrd, xlwt and xlutils

How to edit and save the data in an existing excel workbook using xlrd, xlwt and xlutils module?
could someone please provide a sample code to edit and save the data in excel workbook?
I am trying to put data from one workbook to another.
import xlrd, xlwt, xlutils
wb1 = xlrd.open_workbook('workbook1.xls', formatting_info=True)
wb2 = xlrd.open_workbook('workbook2.xls', formatting_info=True)
value 1 == wb2.sheet_by_name('Sheet1).cell(2,1).value
wb1.sheet_by_name('Sheet1').cell(2,2).value == value1
How to save this data in workbook1.xls?
Sorry, I asked this before, but I am trying to be more clear about my question this time.
Thank you very much.
You can save with wb1.save('workbook1.xls'). You might get an IOError that the file already exists. In that case try to os.remove() the file before saving.
I agree with the previous answer of using the xlwt library save method. But you should also do some proof reading of your code. You are missing a closing quote for Sheet1 and variable names cannot have spaces.

Categories