python operation excel to read the file, and then save processed into new excel

As used herein xlrd, xlwt module, can be installed directly pip install; specific module code can be found on GitHub:  https://github.com/python-excel/xlrd

Detailed description can be referred official website:  http://www.python-excel.org/

Because the two consuming looks above, in order to facilitate the use of quick start, refer to <python used xlrd, xlwt Detailed operation excel spreadsheet> article:  https://www.jb51.net/article/60510.htm

To complete the description herein, the following needs: as shown below, a small amount of data taken, the actual amount of data is more, according to current needs provinces, cut into individual excel file saved up, time-consuming manual operation, consider the code implemented;

Code handling logic:

1. First Use xlrd open the file, the file column values ​​province where all removed, to re-use the set to obtain a set of provinces, traversing provinces;

2. excel Analyzing row by row, if the value of the row of columns equal to said traverse province value, the row is saved, in the same province final data will be saved to a single file;

Specific code as follows:

Import to xlrd, xlwt 
Workbook = xlrd.open_workbook ( ' product_solds_info.xlsx ' , ON_DEMAND = True) # open the file 
sheets workbook.sheets = () # Returns objects iterative sheets 
SH = sheets [0] 

DEF the write_row (WS, SH, index, Cursor):
     for I, V in the enumerate (sh.row_values (index)): 
        ws.write (Cursor, I, V) 
    Cursor = Cursor +. 1
     return Cursor 

cO = sh.col_values (. 8) # reading provinces where entire column contents of the column 
prov_set = SET (cO [. 1:]) # removed name first rank, and provinces deduplication 

for Provin prov_set: 
    WB = xlwt.Workbook () 
    WS = wb.add_sheet ( ' Sheet ' )
     # column name into the first row of 
    the write_row (WS, SH, 0,0) 
    Cursor =. 1
     for RX in Range (sh.nrows) :
         IF sh.row (RX) [. 8] == .Value Prov: 
            Cursor = the write_row (WS, SH, RX, Cursor) 
    wb.save (Prov + ' * .xls ' ) # to province name as the file name stored

 

  

Guess you like

Origin www.cnblogs.com/jason-Gan/p/12034661.html