Points to note when python's openpyxl package reads and saves spreadsheet files

In python, the openpyxl module is often used when manipulating spreadsheets. However, when using the openpyxl module to open or save a spreadsheet file, the usage is as follows:

wb = openpyxl.load_workbook('test.xlsx')
wb.save('test.xlsx')

Two points need attention:
1. The file name should have an extension, such as test.xlsx.
2. The current version of openpyxl does not support .xls files.
3. The file name cannot contain a folder name. For example, the following code will make an error (the reason may be that "\" is regarded as an escape character):

wb = openpyxl.load_workbook('c:\python\test.xlsx')
wb.save('c:\python\test.xlsx')

Therefore, you can use the os.chdir() method to first locate the current folder to the folder where the file is located, and then use the file name string directly as the parameters of the load_workbook() and save() methods. Literal strings can also be used:

wb = openpyxl.load_workbook(r'c:\python\test.xlsx')
wb.save(r'c:\python\test.xlsx')

Additional instructions:
1. When using the remove_sheet(sheetobj) method to remove a worksheet, the sheetobj parameter must be a worksheet object, not a worksheet name string. If you only know the worksheet name, you can use wb['Sheet'] to return the worksheet object. For example:

wb.remove_sheet(wb['Sheet'])

2. The following code does not make an error when executed, but an error occurs when saving the spreadsheet:

sheet.row_dimensions[1] = 20
sheet.column_dimensions['B'] = 20

After modifying to the following code, there is no error no matter whether it is executed or saved:

sheet.row_dimensions[1].height = 20
sheet.column_dimensions['B'].width = 20

3. Insert and delete rows and columns
sheet.insert_rows(num1, num2): insert num2 empty rows before the num1 row
sheet.insert_cols(num1, num2): insert num2 empty columns before the num1 column sheet.delete_rows
(num1, num2) : Delete num2 rows from row num1
sheet.delete_cols(num1,num2): Delete num2 columns from column num1

Guess you like

Origin blog.csdn.net/any1where/article/details/128451531