import xlrd
# 打开文件
workbook = xlrd.open_workbook(r'D:\PycharmProjects\reptile\XLSX 工作表 .xlsx')
# 获取所有sheet
print(workbook.sheet_names()) # ['sheet1', 'sheet2']
# 根据sheet索引或者名称获取sheet内容
sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始
print('222', sheet1.name, sheet1.nrows, sheet1.ncols) # sheet1的名称,行数,列数
order_oumber = sheet1.cell_value(2, 3) # 第三行第四列
# 获取整行和整列的值(数组)
rows = sheet1.row_values(4) # 获取第四行内容
cols = sheet1.col_values(3) # 获取第三列内容
print('333', rows)
print('444', cols)
# 获取单元格内容,三种方法
print(sheet1.cell(1, 3).value.encode('utf-8'))
print(sheet1.cell_value(1, 3))
print(sheet1.row(1)[3])
import xlwt
"""这种方法会清空文件原有的内容"""
workbook = xlwt.Workbook(encoding='utf-8')
booksheet = workbook.add_sheet('Sheet 1', cell_overwrite_ok=True)
# 存第一行cell(1,1)和cell(1,2)
booksheet.write(0, 0, 34) # 第一行第一列
booksheet.write(0, 2, 55) # 第一行第三列
booksheet.write(2, 2, 555) # 第三行第三列
rowdata = [12, 13, 14]
for i in range(len(rowdata)):
booksheet.write(8, i, rowdata[i]) # 第9行1,2,3列存入12,13,14
workbook.save('XLSX 工作表111.xlsx') # 保存文件名
from xlutils.copy import copy
"""这种是追加写入数据,不清空原有的数据"""
workbook1 = xlrd.open_workbook(r'D:\PycharmProjects\reptile\XLSX 工作表 - 副本.xlsx') # 文件路径
xlsc = copy(workbook1)
shtc = xlsc.get_sheet(0)
# (行,列,要追加的值)
shtc.write(5, 1, "追加得数11")
shtc.write(5, 5, "追加得数22")
shtc.write(5, 9, "追加得数33")
shtc.write(5, 8, "追加得数44")
xlsc.save('XLSX 工作表 - 副本.xlsx') # 保存文件名
import pandas as pd
"""存数据"""
csv_mat = pd.np.empty((0, 2), float)
csv_mat = pd.np.append(csv_mat, [[43, 55]], axis=0)
csv_mat = pd.np.append(csv_mat, [[65, 67]], axis=0)
csv_pd = pd.DataFrame(csv_mat)
csv_pd.to_csv("tests.csv", sep=',', header=False, index=False)
"""取数据"""
filename = r"D:\PycharmProjects\reptile\tests.csv"
csv_data = pd.read_csv(filename, header=None)
csv_data = pd.np.array(csv_data, dtype=float)
import xlsxwriter
for i in range(1, 21):
book = xlsxwriter.Workbook("000 .xls") # 保存的文件名
sheet = book.add_worksheet('demo')
print(i)
sheet.insert_image('B' + str(i), r"D:\PycharmProjects\reptile\图片\\" + str(i) + '.jpg') # 存入表格的位置和图片的路径
book.close()
import pandas as pd
def writeDataIntoExcel(xlsPath: str, data: dict):
writer = pd.ExcelWriter(xlsPath)
sheetNames = data.keys() # 获取所有sheet的名称
# sheets是要写入的excel工作簿名称列表
data = pd.DataFrame(data)
for sheetName in sheetNames:
data.to_excel(writer, sheet_name=sheetName)
# 保存writer中的数据至excel
# 如果省略该语句,则数据不会写入到上边创建的excel文件中
writer.save()
if __name__ == '__main__':
data = {"name":["lily","ailcie"],"cost":[100,20]}
xlspath = "3.xls"
writeDataIntoExcel(xlspath,data)