Use python to read and write excel files

1. Start by reading the excel sheet.

    Read the excel table with the xlrd library, this pip install xlrd will do

    After installing the xlrd library, we can start reading.

Look at the following code:

data = xlrd.open_workbook('brief1.xls')

The open_workbook() method of the xlrd library can access the excel file and return a file object.

table = data.sheets()[0]

The [0] after the sheets method represents the first sheet, such as the following figure

, where sheets()[0] means sheet_name, and sheets()[1] means Sheet1

And the sheets() method will return a table object, so we can also get the number of rows or columns of a table through this object

rows = table.nrows

The nrows of the table object is used to get the number of rows.

So now we know how to get the excel object, the table object, the number of rows or columns, so how do we get the elements in the table.

Here we have a method dedicated to getting table elements, which is row_value(i)[index]

, we see that there are three values ​​in this table, and they are all in the first column,

At this time, we can use the row_value()[] method of the table object to obtain the object. The specific operations are as follows

name = table.row_values(i)[0]

i is the loop variable, because we want to read the three elements in the table, so we know that this i actually represents a row, then [0] is obviously a column,

So here the parentheses represent rows, square brackets represent columns, (0)[0] represents the first of the first column, and (1)[0] represents the second of the first column.

Then read the excel sheet and that's it.



2. Write data into excel sheet

    There is a special library xlrd for reading excel, and of course there is a special library for writing excel. This library is xlwt, and the installation is the same as above.

    So before writing to the database, we first create a new excel file

file = xlwt.Workbook()

Note that the W should be capitalized.

Then after getting the object of the excel file, we also need to create the table

table = file.add_sheet('sheet name')

The table object is obtained by the add_sheet method of the file object. Next, we can naturally think of using the table object to write data.

table.write(0,0,'test')
table.write(1,0,'test')

Run it and see:

, so the first parameter of write represents the row, the second parameter represents the column, and the third parameter represents the value to be written,

And the writing here is the same as when we read it, the parameters of the row are in the front and the columns are in the back.

Then, of course, after writing is completed, it is saved.

You can directly use the save method of the file object, that is, file.save(str), and the parameter is the file name.

So this time about the basic operation of python on excel is here.

thanks.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325736437&siteId=291194637