导包:
import xlsxwriter import openpyxl
新建、上传和修改.xlsx文件
# 新建标1.xlsx文件
file_name = r"C:\Users\ityw\PycharmProjects\pythonProject8\other\标1.xlsx"
workbook = xlsxwriter.Workbook(file_name)
worksheet = workbook.add_worksheet('sheet1')
worksheet.write_row(0, 0, ['广告','广告词','广告词','前缀','前缀词','前缀词',
'是否力荐','简介']) #第一行
worksheet.write_row(1, 0, ['18', '21', '8', '9999910', '1', '20010']) # 第二行
worksheet.write_row(2, 0, ['18', '21', '8', '9999911', '1', '20010']) # 第三行
workbook.close()
# 上传标1.xlsx文件
fields = {"files": ("标1.xlsx", open(r"C:\Users\ityw\PycharmProjects\pythonProject8\other\标1.xlsx",
"rb"),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}
response6 = requests.post(url="http://xxx/api/other/tasklistfile/multifileUpload",
files=fields,
data={"sheetType": "GOODS"},
headers={"apptoken": apptoken, "entId": "1", "postId": postId, "appId": appId})
r6 = response6.json()
print(f"r6:{r6}")
# 修改标1.xlsx文件
wb = openpyxl.load_workbook(r"C:\Users\ityw\PycharmProjects\pythonProject8\other\标1.xlsx")
ws = wb['Sheet1']
ws.cell(2, 6).value = 20010 #修改第2行第6列的数据
ws.cell(3, 6).value = 20010 #修改第3行第6列的数据
wb.save(r"C:\Users\ityw\PycharmProjects\pythonProject8\other\标1.xlsx")
上传文件的时候有遇到报错:
java.sql.SQLException:字段'sheet_type'没有默认值\n;字段'sheet_type'没有默认值
这是因为请求参数缺失问题,抓包数据中没有留意到sheetType这个字段的信息
------WebKitFormBoundary2tynKBFOEw8dbiiI
Content-Disposition: form-data; name="sheetType"
CHANNEL_GOODS
------WebKitFormBoundary2tynKBFOEw8dbiiI--
后面加上 data={"sheetType": "CHANNEL_GOODS"} ,再次请求后上传文件成功。
修改.xlsx文件时,遇到报错:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
这是因为打开文件的地址需要处理,在前面加r,成功解决报错。
参考文档地址:
https://blog.csdn.net/weixin_45835837/article/details/120524301 ---python 处理.xlsx文件
https://blog.csdn.net/Telfort/article/details/115403175 ---python上传excel文件