# -*- coding: utf-8 -*- import xdrlib ,sys import xlrd def open_excel(file= 'file.xls'): try: data = xlrd.open_workbook(file) return data except Exception as e: print (str(e)) #根據索引獲取Excel表格中的數據 參數:file:Excel文件路徑 colnameindex:表頭列名所在行的因此 ,by_index:表的索引 def excel_table_byindex(file= 'file.xls',colnameindex=0,by_index=0): data = open_excel(file) table = data.sheets()[by_index] nrows = table.nrows #行數 ncols = table.ncols #列數 colnames = table.row_values(colnameindex) #某一行數據 list =[] for rownum in range(1,nrows): row = table.row_values(rownum) if row: app = {} for i in range(len(colnames)): app[colnames[i]] = row[i] list.append(app) return list #根據名稱獲取Excel表格中的數據 參數:file:Excel文件路徑 colnameindex:表頭列名所在行的因此 ,by_name:Sheet1名稱 # def excel_table_byname(file= 'file.xls',colnameindex=0,by_name=u'Sheet1'): # data = open_excel(file) # table = data.sheet_by_name(by_name) # nrows = table.nrows #行數 # colnames = table.row_values(colnameindex) #某一行數據 # list =[] # for rownum in range(1,nrows): # row = table.row_values(rownum) # if row: # app = {} # for i in range(len(colnames)): # app[colnames[i]] = row[i] # list.append(app) # return list def main(): tables = excel_table_byindex() for row in tables: print (row) # tables = excel_table_byname() # for row in tables: # print (row) if __name__=="__main__": main()
# -*- coding: utf-8 -*- # 導入xlwt模塊 import xlwt # 建立一個Workbook對象,這就至關於建立了一個Excel文件 book = xlwt.Workbook(encoding='utf-8', style_compression=0) ''' Workbook類初始化時有encoding和style_compression參數 encoding:設置字符編碼,通常要這樣設置:w = Workbook(encoding='utf-8'),就能夠在excel中輸出中文了。 默認是ascii。固然要記得在文件頭部添加: #!/usr/bin/env python # -*- coding: utf-8 -*- style_compression:表示是否壓縮,不經常使用。 ''' # 建立一個sheet對象,一個sheet對象對應Excel文件中的一張表格。 # 在電腦桌面右鍵新建一個Excel文件,其中就包含sheet1,sheet2,sheet3三張表 sheet = book.add_sheet('test', cell_overwrite_ok=True) # 其中的test是這張表的名字,cell_overwrite_ok,表示是否能夠覆蓋單元格,實際上是Worksheet實例化的一個參數,默認值是False # 向表test中添加數據 sheet.write(0, 0, 'EnglishName') # 其中的'0-行, 0-列'指定表中的單元,'EnglishName'是向該單元寫入的內容 sheet.write(1, 0, 'Marcovaldo') txt1 = '中文名字' sheet.write(0, 1, txt1.encode().decode('utf-8')) # 此處須要將中文字符串解碼成unicode碼,不然會報錯 txt2 = '馬可瓦多' sheet.write(1, 1, txt2.encode().decode('utf-8')) # 最後,將以上操做保存到指定的Excel文件中 book.save(r'f:\test1.xls') # 在字符串前加r,聲明爲raw字符串,這樣就不會處理其中的轉義了。不然,可能會報錯
#!/usr/bin/env python3 # encoding=UTF-8 import os import time import xlwt hostIp = '127.0.0.1' user = 'root' passwd = 'root' db = 'cities' sqlStr1 = 'SELECT * FROM city' def createTable(selectSql, tableName): # 鏈接數據庫,執行sql results = os.popen( 'mysql -h' + hostIp + ' -u' + user + ' -p' + passwd + ' -D' + db + ' -e "' + selectSql + '"').read().strip().split( '\n') # 獲取列名 columnName = results[0].split('\t') # 建立一個excel工做簿,編碼utf-8,表格中支持中文 wb = xlwt.Workbook(encoding='utf-8') # 建立一個sheet sheet = wb.add_sheet('sheet 1') # 獲取行數 rows = len(results) # 獲取列數 columns = len(columnName) # 建立格式style style = xlwt.XFStyle() # 建立font,設置字體 font = xlwt.Font() # 字體格式 font.name = 'Times New Roman' # 將字體font,應用到格式style style.font = font # 建立alignment,居中 alignment = xlwt.Alignment() # 居中 alignment.horz = xlwt.Alignment.HORZ_CENTER # 應用到格式style style.alignment = alignment style1 = xlwt.XFStyle() font1 = xlwt.Font() font1.name = 'Times New Roman' # 字體顏色(綠色) # font1.colour_index = 3 # 字體加粗 font1.bold = True style1.font = font1 style1.alignment = alignment for i in range(columns): # 設置列的寬度 sheet.col(i).width = 5000 # 插入列名 for i in range(columns): sheet.write(0, i, columnName[i], style1) # 將數據插入表格 for i in range(1, rows): for j in range(columns): sheet.write(i, j, results[i].split('\t')[j], style) # 保存表格,並命名爲‘xxxx’戶.xls wb.save(tableName) # 獲取當前時間 excelTime = time.strftime("%Y%m%d") createTable(sqlStr1, excelTime + 'database.xls')
4.xlrd讀.xsl保存到mysql某張表python
#!/usr/bin/env python3 #coding=utf-8 import pymysql import os import time import xlrd host = '127.0.0.1' port = 3306 user = 'root' passwd = 'root' db = 'cities' db_table = 'city2' file='20180909database.xls' by_index= 0 colnameindex=0 def open_excel(file): # 獲取excel數據 try: data = xlrd.open_workbook(file) return data except Exception as e: print (str(e)) def mysql_sql(host=host,port=port,user=user,passwd=passwd,db_table=db_table,db=db,file= file,colnameindex=colnameindex,by_index=by_index): # 鏈接數據庫 pymysql.install_as_MySQLdb() conn = pymysql.connect( host=host, port=port, user=user, passwd=passwd, db=db, ) cur = conn.cursor() # 獲取excel data = open_excel(file) table = data.sheets()[by_index] nrows = table.nrows #行數 ncols = table.ncols # 列數 # colnames = table.row_values(colnameindex) #標題數據 list =[] for rownum in range(0,nrows): row = table.row_values(rownum) if row: if rownum == 0: # 建立表和字段 list_ziduan = '' for i in range(ncols): if table.row_values(rownum)[i] == 'id': list_ziduan = list_ziduan+table.row_values(rownum)[i]+' int,' else: list_ziduan = list_ziduan+table.row_values(rownum)[i]+' VARCHAR(100),' cur.execute(("create table " + db_table + "(" + list_ziduan[:-1] + " )")) # 添加字段名稱 # for i in range(len(colnames)): # insertOne = 'ALERT TABLE ' + db_table + " ADD " + row[i] + ' not Null;' # cur.execute(insertOne) # list.append(insertOne) else: # 添加數據 tupleToStr = tuple(table.row_values(rownum)).__str__() insertOne ='INSERT INTO '+db_table+" VALUES "+tupleToStr+';' cur.execute(insertOne) list.append(insertOne) cur.close() conn.commit() conn.close() return list def main(): tables = mysql_sql(host=host,port=port,user=user,passwd=passwd,db_table=db_table,db=db,file= file,colnameindex=colnameindex,by_index=by_index) for row in tables: print (row) if __name__=="__main__": main()