feishu.py 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  1. # -*- coding: UTF-8 -*-
  2. import json
  3. import base64
  4. import hashlib
  5. import os
  6. from curl_cffi import requests as mj_requests
  7. import requests
  8. import os
  9. from dotenv import load_dotenv, find_dotenv
  10. load_dotenv(find_dotenv())
  11. # load from env
  12. APP_ID = 'cli_a22acf2916b8500e'
  13. APP_SECRET = 'tE0xAB2gZTMlBGdPczCGLcmpRlZQm5CQ'
  14. LARK_HOST = 'https://open.feishu.cn'
  15. APP_HOST = 'https://open.feishu.cn'
  16. EMAIL = 'semsevens@email.com'
  17. class LarkException(Exception):
  18. def __init__(self, code=0, msg=None):
  19. self.code = code
  20. self.msg = msg
  21. def __str__(self) -> str:
  22. return "{}:{}".format(self.code, self.msg)
  23. __repr__ = __str__
  24. def request(method, url, headers, payload={}):
  25. response = requests.request(method, url, headers=headers, json=payload)
  26. # logging.info("URL: " + url)
  27. # logging.info("X-Tt-Logid: " + response.headers['X-Tt-Logid'])
  28. # logging.info("headers:\n"+json.dumps(headers,indent=2, ensure_ascii=False))
  29. # logging.info("payload:\n"+json.dumps(payload,indent=2, ensure_ascii=False))
  30. resp = {}
  31. if response.text[0] == '{':
  32. resp = response.json()
  33. # logging.info("response:\n"+json.dumps(resp,indent=2, ensure_ascii=False))
  34. else:
  35. pass
  36. # logging.info("response:\n"+response.text)
  37. code = resp.get("code", -1)
  38. if code == -1:
  39. code = resp.get("StatusCode", -1)
  40. if code == -1 and response.status_code != 200:
  41. response.raise_for_status()
  42. if code != 0:
  43. raise LarkException(code=code, msg=resp.get("msg", ""))
  44. return resp
  45. def get_image_data_from_url(img_url, use_cache=True):
  46. # 计算URL的MD5哈希值
  47. url_hash = hashlib.md5(img_url.encode()).hexdigest()
  48. cache_dir = 'image_cache'
  49. cache_file = os.path.join(cache_dir, f'{url_hash}.json')
  50. if use_cache:
  51. # 检查缓存目录是否存在,如果不存在则创建
  52. if not os.path.exists(cache_dir):
  53. os.makedirs(cache_dir)
  54. # 检查缓存文件是否存在
  55. if os.path.exists(cache_file):
  56. with open(cache_file, 'r') as f:
  57. cached_data = json.load(f)
  58. return cached_data['image_data']
  59. # 如果缓存不存在,从URL获取图片
  60. if 'midjourney' in img_url:
  61. proxies = {
  62. 'http': 'http://127.0.0.1:7890',
  63. 'https': 'http://127.0.0.1:7890',
  64. }
  65. # response = mj_requests.get(img_url, impersonate="chrome100", proxies=proxies)
  66. response = mj_requests.get(img_url.replace("https://", "http://"), impersonate="chrome100")
  67. else:
  68. # proxies = {
  69. # 'http': 'http://t10952018781111:1ap37oc3@d844.kdltps.com:15818',
  70. # 'https': 'http://t10952018781111:1ap37oc3@d844.kdltps.com:15818',
  71. # }
  72. # proxies = {
  73. # 'http': None,
  74. # 'https': None,
  75. # }
  76. # response = requests.get(img_url.replace("https://", "http://"), proxies=proxies)
  77. response = requests.get(img_url)
  78. # response = requests.get(img_url, proxies=proxies)
  79. if response.status_code == 200:
  80. image_content = response.content
  81. missing_padding = 4 - len(image_content) % 4
  82. if missing_padding:
  83. image_content += b'=' * missing_padding
  84. image_data = base64.b64encode(image_content).decode('utf-8')
  85. # 将图片数据保存到缓存
  86. with open(cache_file, 'w') as f:
  87. json.dump({'image_data': image_data}, f)
  88. return image_data
  89. else:
  90. # import traceback
  91. # traceback.print_exc()
  92. raise Exception(f"无法从URL获取图片: {img_url}")
  93. from PIL import Image
  94. import io
  95. import os
  96. def get_image_size(img_url):
  97. img_data = get_image_data_from_url(img_url)
  98. img = Image.open(io.BytesIO(base64.b64decode(img_data)))
  99. width, height = img.size
  100. return width, height
  101. if __name__ == "__main__":
  102. img_url = "https://sns-webpic.xhscdn.com/1040g2sg31c4vs26n12a05ph3cdp3cutm5prqo90"
  103. img_data = get_image_data_from_url(img_url)
  104. save_path = "/Users/nieqi/Downloads/save.json"
  105. with open(save_path, 'w') as f:
  106. f.write(img_data)
  107. def column_id(col):
  108. '''column int to string id'''
  109. ans = ""
  110. i = col
  111. while i > 0:
  112. m = int((i-1) % 26)
  113. i = int((i-1) / 26)
  114. ans = chr(m+65) + ans
  115. return ans
  116. def do_compress_image(image_data, image_type):
  117. # 压缩图片
  118. from PIL import Image
  119. import io
  120. import base64
  121. Image.MAX_IMAGE_PIXELS = None # 禁用图片大小限制
  122. # 将base64转为图片对象
  123. image = Image.open(io.BytesIO(base64.b64decode(image_data)))
  124. # 计算压缩后的尺寸,保持宽高比
  125. max_size = 1600
  126. ratio = min(max_size/image.width, max_size/image.height)
  127. if ratio < 1:
  128. new_size = (int(image.width * ratio), int(image.height * ratio))
  129. image = image.resize(new_size, Image.Resampling.LANCZOS)
  130. # 在保存之前转换RGBA为RGB
  131. if image.mode == 'RGBA':
  132. # 创建白色背景
  133. background = Image.new('RGB', image.size, (255, 255, 255))
  134. # 将RGBA图片合成到白色背景上
  135. background.paste(image, mask=image.split()[3]) # 使用alpha通道作为mask
  136. image = background
  137. buffer = io.BytesIO()
  138. # 将 'JPG' 转换为 'JPEG'
  139. if image_type and image_type.upper() == 'JPG':
  140. image_type = 'JPEG'
  141. image_type = 'JPEG'
  142. # image.save(buffer, format=image_type.upper(), quality=95, optimize=True)
  143. image.save(buffer, format=image_type.upper(), quality=85, optimize=True)
  144. image_data = base64.b64encode(buffer.getvalue()).decode()
  145. return image_data
  146. class Client(object):
  147. def __init__(self, lark_host):
  148. self._host = lark_host
  149. def get_tenant_access_token(self, app_id, app_secret):
  150. url = self._host+"/open-apis/auth/v3/app_access_token/internal/"
  151. headers = {
  152. 'Content-Type': 'application/json; charset=utf-8'
  153. }
  154. payload = {
  155. 'app_id': app_id,
  156. 'app_secret': app_secret
  157. }
  158. resp = request("POST", url, headers, payload)
  159. return resp['tenant_access_token']
  160. def get_user_access_token(self, tenant_access_token, code):
  161. url = self._host+"/open-apis/authen/v1/access_token"
  162. headers = {
  163. 'Content-Type': 'application/json; charset=utf-8'
  164. }
  165. payload = {
  166. "grant_type": "authorization_code",
  167. "code": code,
  168. "app_access_token": tenant_access_token
  169. }
  170. resp = request("POST", url, headers, payload)
  171. return resp['data']['access_token']
  172. def get_root_folder_token(self, access_token):
  173. url = self._host+"/open-apis/drive/explorer/v2/root_folder/meta"
  174. headers = {
  175. 'Content-Type': 'application/json; charset=utf-8',
  176. 'Authorization': 'Bearer '+access_token
  177. }
  178. resp = request("GET", url, headers)
  179. return resp['data']['token']
  180. def create_spreadsheet(self, access_token, foldertoken, title):
  181. url =self._host+"/open-apis/sheets/v3/spreadsheets"
  182. headers = {
  183. 'Content-Type': 'application/json; charset=utf-8',
  184. 'Authorization': 'Bearer '+access_token
  185. }
  186. payload={
  187. "title": title,
  188. "folder_token": foldertoken
  189. }
  190. resp = request("POST", url, headers, payload)
  191. return resp['data']['spreadsheet']['spreadsheet_token'], resp['data']['spreadsheet']['url']
  192. def get_sheetid(self, access_token, doctoken, sheet_index=0):
  193. url = self._host+"/open-apis/sheets/v2/spreadsheets/"+doctoken+"/metainfo"
  194. headers = {
  195. 'Content-Type': 'application/json; charset=utf-8',
  196. 'Authorization': 'Bearer '+access_token
  197. }
  198. resp = request("GET", url, headers)
  199. return resp['data']['sheets'][sheet_index]["sheetId"]
  200. def batch_update_values(self, access_token, doctoken, data):
  201. url =self._host+"/open-apis/sheets/v2/spreadsheets/"+doctoken+"/values_batch_update"
  202. headers = {
  203. 'Content-Type': 'application/json; charset=utf-8',
  204. 'Authorization': 'Bearer '+access_token
  205. }
  206. payload=data
  207. resp = request("POST", url, headers, payload)
  208. return resp['data']['spreadsheetToken']
  209. def batch_update_styles(self, access_token, doctoken, data):
  210. url =self._host+"/open-apis/sheets/v2/spreadsheets/"+doctoken+"/styles_batch_update"
  211. headers = {
  212. 'Content-Type': 'application/json; charset=utf-8',
  213. 'Authorization': 'Bearer '+access_token
  214. }
  215. payload=data
  216. resp = request("PUT", url, headers, payload)
  217. return resp['data']['spreadsheetToken']
  218. def add_permissions_member(self, access_token, doctoken, doctype, member_type, member_id, perm):
  219. url = self._host+"/open-apis/drive/v1/permissions/"+doctoken+"/members?type="+doctype+"&need_notification=false"
  220. headers = {
  221. 'Content-Type': 'application/json; charset=utf-8',
  222. 'Authorization': 'Bearer '+access_token
  223. }
  224. payload = {
  225. "member_type": member_type,
  226. "member_id": member_id,
  227. "perm": perm
  228. }
  229. request("POST", url, headers, payload)
  230. def write_image_to_cell(self, access_token, doctoken, sheetid, img_url, row, col, image_type, compress_image=True):
  231. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/values_image"
  232. headers = {
  233. 'Content-Type': 'application/json; charset=utf-8',
  234. 'Authorization': f'Bearer {access_token}'
  235. }
  236. try:
  237. image_data = get_image_data_from_url(img_url)
  238. except Exception as e:
  239. print(img_url)
  240. print(e)
  241. return None, None
  242. if compress_image:
  243. image_data = do_compress_image(image_data, image_type)
  244. image_name = img_url.split('/')[-1].replace(f'.{image_type}', '') # 从URL中提取文件名
  245. if compress_image:
  246. image_type = 'JPEG'
  247. cell_start = column_id(col)+str(row)
  248. range = f'{sheetid}!{cell_start}:{cell_start}'
  249. payload = {
  250. "range": range,
  251. "image": image_data,
  252. "name": f"{image_name}.{image_type}"
  253. }
  254. try:
  255. resp = request("POST", url, headers, payload)
  256. except Exception as e:
  257. print(img_url)
  258. print(image_name)
  259. print(image_type)
  260. print(e)
  261. return None, None
  262. return resp['data']['revision'], resp['data']['updateRange']
  263. def merge_cells(self, access_token, doctoken, sheetid, start_row, end_row, start_col, end_col):
  264. print(f"merge start_row = {start_row} end_row = {end_row} start_col = {start_col} end_col = {end_col}")
  265. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/merge_cells"
  266. headers = {
  267. 'Content-Type': 'application/json; charset=utf-8',
  268. 'Authorization': f'Bearer {access_token}'
  269. }
  270. start_col_id = column_id(start_col)
  271. end_col_id = column_id(end_col)
  272. payload = {
  273. "range": f"{sheetid}!{start_col_id}{start_row}:{end_col_id}{end_row}",
  274. "mergeType": "MERGE_ALL",
  275. }
  276. try:
  277. resp = request("POST", url, headers, payload)
  278. except Exception as e:
  279. print(e)
  280. return None
  281. return None
  282. def write_images_to_cell(self, access_token, doctoken, sheetid, img_url_list, row, col, compress_image=True, grid_width=None, grid_height=None, border_width=3, border_color=(200, 200, 200)):
  283. """
  284. 将多张图片拼接后写入单元格
  285. Args:
  286. img_url_list: 图片URL列表
  287. row: 目标单元格行号
  288. col: 目标单元格列号
  289. compress_image: 是否压缩图片
  290. grid_width: 拼接图片的列数,如果为None则自动计算
  291. grid_height: 拼接图片的行数,如果为None则自动计算
  292. border_width: 边框宽度,像素
  293. border_color: 边框颜色,RGB元组
  294. """
  295. from PIL import Image, ImageDraw
  296. import io
  297. import base64
  298. import math
  299. # 下载所有图片
  300. images = []
  301. for img_url in img_url_list:
  302. try:
  303. image_type = get_image_type(img_url)
  304. if not image_type:
  305. continue
  306. image_data = get_image_data_from_url(img_url)
  307. image = Image.open(io.BytesIO(base64.b64decode(image_data)))
  308. images.append(image)
  309. except Exception as e:
  310. print(f"下载图片失败: {img_url}")
  311. print(e)
  312. continue
  313. if not images:
  314. return None, None
  315. # 计算拼接图片的行列数
  316. img_count = len(images)
  317. if grid_width is None and grid_height is None:
  318. # 如果未指定行列数,计算最接近正方形的网格
  319. grid_width = math.ceil(math.sqrt(img_count))
  320. grid_height = math.ceil(img_count / grid_width)
  321. elif grid_width is None:
  322. # 如果只指定了行数,计算列数
  323. grid_width = math.ceil(img_count / grid_height)
  324. elif grid_height is None:
  325. # 如果只指定了列数,计算行数
  326. grid_height = math.ceil(img_count / grid_width)
  327. # 确保网格能容纳所有图片
  328. while grid_width * grid_height < img_count:
  329. if grid_width <= grid_height:
  330. grid_width += 1
  331. else:
  332. grid_height += 1
  333. # 调整所有图片到相同尺寸,保持原始比例
  334. if images:
  335. # 计算目标尺寸(使用平均尺寸作为参考)
  336. avg_width = sum(img.width for img in images) // len(images)
  337. avg_height = sum(img.height for img in images) // len(images)
  338. target_size = (avg_width, avg_height)
  339. # 调整图片尺寸,保持原始比例
  340. resized_images = []
  341. for img in images:
  342. # 计算保持比例的缩放尺寸
  343. img_ratio = img.width / img.height
  344. target_ratio = target_size[0] / target_size[1]
  345. if img_ratio > target_ratio:
  346. # 图片比目标更宽,以宽度为准
  347. new_width = target_size[0]
  348. new_height = int(target_size[0] / img_ratio)
  349. else:
  350. # 图片比目标更高,以高度为准
  351. new_height = target_size[1]
  352. new_width = int(target_size[1] * img_ratio)
  353. # 缩放图片,保持比例
  354. resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
  355. resized_images.append(resized_img)
  356. # 创建拼接画布
  357. canvas_width = grid_width * avg_width + (grid_width + 1) * border_width
  358. canvas_height = grid_height * avg_height + (grid_height + 1) * border_width
  359. canvas = Image.new('RGB', (canvas_width, canvas_height), border_color)
  360. # 拼接图片
  361. for i, img in enumerate(resized_images):
  362. row_idx = i // grid_width
  363. col_idx = i % grid_width
  364. # 计算每个网格单元的位置
  365. cell_x = col_idx * avg_width + (col_idx + 1) * border_width
  366. cell_y = row_idx * avg_height + (row_idx + 1) * border_width
  367. # 在网格单元中居中放置图片
  368. center_x = cell_x + (avg_width - img.width) // 2
  369. center_y = cell_y + (avg_height - img.height) // 2
  370. canvas.paste(img, (center_x, center_y))
  371. # 将拼接后的图片转换为base64
  372. output = io.BytesIO()
  373. if compress_image:
  374. canvas.save(output, format='JPEG', quality=85)
  375. image_type = 'JPEG'
  376. else:
  377. canvas.save(output, format='PNG')
  378. image_type = 'PNG'
  379. output.seek(0)
  380. image_data = base64.b64encode(output.getvalue()).decode()
  381. # 调用写入图片的API
  382. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/values_image"
  383. headers = {
  384. 'Content-Type': 'application/json; charset=utf-8',
  385. 'Authorization': f'Bearer {access_token}'
  386. }
  387. cell_start = column_id(col) + str(row)
  388. range_val = f'{sheetid}!{cell_start}:{cell_start}'
  389. payload = {
  390. "range": range_val,
  391. "image": image_data,
  392. "name": f"combined_image.{image_type}"
  393. }
  394. try:
  395. resp = request("POST", url, headers, payload)
  396. return resp['data']['revision'], resp['data']['updateRange']
  397. except Exception as e:
  398. print(f"写入拼接图片失败: {e}")
  399. return None, None
  400. return None, None
  401. def read_range_values(self, access_token, doctoken, range_val):
  402. """
  403. 读取指定范围的数据
  404. Args:
  405. access_token: 访问令牌
  406. doctoken: 表格token
  407. range_val: 范围,格式如 "Sheet1!A1:C10"
  408. Returns:
  409. 读取到的数据列表
  410. """
  411. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/values/{range_val}"
  412. headers = {
  413. 'Content-Type': 'application/json; charset=utf-8',
  414. 'Authorization': f'Bearer {access_token}'
  415. }
  416. try:
  417. resp = request("GET", url, headers)
  418. return resp['data']['valueRange']['values']
  419. except Exception as e:
  420. print(f"读取数据失败: {e}")
  421. return []
  422. def prepend_data(self, access_token, doctoken, range_val, values):
  423. """
  424. 在指定位置前面插入数据
  425. Args:
  426. access_token: 访问令牌
  427. doctoken: 表格token
  428. range_val: 插入范围,格式如 "Sheet1!A1:C1"
  429. values: 要插入的数据
  430. Returns:
  431. 操作结果
  432. """
  433. url = f"{self._host}/open-apis/sheets/v3/spreadsheets/{doctoken}/sheets/{range_val.split('!')[0]}/prepend"
  434. headers = {
  435. 'Content-Type': 'application/json; charset=utf-8',
  436. 'Authorization': f'Bearer {access_token}'
  437. }
  438. # 从range_val中提取行数
  439. range_part = range_val.split('!')[1] # 如 "A1:Z1"
  440. start_cell = range_part.split(':')[0] # 如 "A1"
  441. payload = {
  442. "values": values
  443. }
  444. try:
  445. resp = request("POST", url, headers, payload)
  446. return resp
  447. except Exception as e:
  448. print(f"插入数据失败: {e}")
  449. return None
  450. def insert_data_at_row(self, access_token, doctoken, sheetid, row, values):
  451. """
  452. 在指定行插入数据(使用批量更新方式)
  453. Args:
  454. access_token: 访问令牌
  455. doctoken: 表格token
  456. sheetid: 工作表ID
  457. row: 目标行号
  458. values: 要插入的数据
  459. Returns:
  460. 操作结果
  461. """
  462. # 使用批量更新的方式插入数据
  463. cols = len(values[0]) if values else 1
  464. end_col = column_id(cols)
  465. range_val = f"{sheetid}!A{row}:{end_col}{row}"
  466. body = {
  467. "valueRanges": [
  468. {
  469. "range": range_val,
  470. "values": values
  471. }
  472. ]
  473. }
  474. try:
  475. result = self.batch_update_values(access_token, doctoken, body)
  476. return result
  477. except Exception as e:
  478. print(f"插入数据到第{row}行失败: {e}")
  479. return None
  480. def insert_rows_before(self, access_token, doctoken, sheetid, row_index, count=1):
  481. """
  482. 在指定行前插入新行(基于飞书官方API)
  483. Args:
  484. access_token: 访问令牌
  485. doctoken: 表格token
  486. sheetid: 工作表ID
  487. row_index: 插入位置的行号(从1开始,在此行前插入)
  488. count: 插入行数(默认1行)
  489. Returns:
  490. 操作结果
  491. """
  492. # 先获取工作表信息,检查当前行数
  493. sheet_props = self.get_sheet_properties(access_token, doctoken, sheetid)
  494. if not sheet_props:
  495. print("无法获取工作表信息,尝试直接插入")
  496. current_row_count = 1000 # 默认值
  497. else:
  498. current_row_count = sheet_props['row_count']
  499. print(f"当前工作表行数: {current_row_count}")
  500. # 如果要插入的位置超过了当前行数,使用追加模式
  501. if row_index > current_row_count:
  502. print(f"插入位置({row_index})超过当前行数({current_row_count}),使用追加模式")
  503. # 使用追加方式在末尾添加行
  504. return self.append_empty_rows(access_token, doctoken, sheetid, count)
  505. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/insert_dimension_range"
  506. headers = {
  507. 'Content-Type': 'application/json; charset=utf-8',
  508. 'Authorization': f'Bearer {access_token}'
  509. }
  510. # 转换为0基索引:row_index=3表示第3行,对应startIndex=2
  511. start_index = row_index - 1 # 从0开始计数
  512. end_index = start_index + count # 结束位置(不包含)
  513. # 确保 endIndex 不超过当前工作表的行数限制
  514. if end_index > current_row_count:
  515. print(f"警告:计算的endIndex({end_index})超过当前行数({current_row_count}),调整为追加模式")
  516. return self.append_empty_rows(access_token, doctoken, sheetid, count)
  517. # 智能选择继承样式:插入第2行时继承后面的数据行样式,其他情况继承前面的样式
  518. inherit_style = "AFTER" if row_index == 2 else "BEFORE"
  519. payload = {
  520. "dimension": {
  521. "sheetId": sheetid,
  522. "majorDimension": "ROWS",
  523. "startIndex": start_index, # 从0开始计数
  524. "endIndex": end_index # 结束位置(不包含此行)
  525. },
  526. "inheritStyle": inherit_style # 智能继承样式
  527. }
  528. try:
  529. resp = request("POST", url, headers, payload)
  530. print(f"在第{row_index}行前成功插入{count}行(startIndex={start_index}, endIndex={end_index}, inheritStyle={inherit_style})")
  531. return resp
  532. except Exception as e:
  533. print(f"在第{row_index}行前插入{count}行失败: {e}")
  534. # 如果插入失败,尝试追加模式
  535. print("尝试使用追加模式...")
  536. return self.append_empty_rows(access_token, doctoken, sheetid, count)
  537. def insert_row_with_images(self, access_token, doctoken, sheetid, row, values, compress_image=True, grid_width=None, grid_height=None, border_width=3, border_color=(200, 200, 200)):
  538. """
  539. 在指定行插入数据并同时处理图片写入(覆盖方式)
  540. Args:
  541. access_token: 访问令牌
  542. doctoken: 表格token
  543. sheetid: 工作表ID
  544. row: 目标行号
  545. values: 要插入的数据
  546. compress_image: 是否压缩图片
  547. grid_width: 拼接图片的列数
  548. grid_height: 拼接图片的行数
  549. border_width: 边框宽度
  550. border_color: 边框颜色
  551. Returns:
  552. 操作结果
  553. """
  554. # 1. 先插入文本数据(覆盖指定行)
  555. result = self.insert_data_at_row(access_token, doctoken, sheetid, row, values)
  556. if not result:
  557. return None
  558. # 2. 同时处理图片写入
  559. if values and len(values) > 0:
  560. row_data = values[0]
  561. for col_index, cell in enumerate(row_data, start=1):
  562. if is_image_list_cell_url(cell):
  563. # 处理图片列表
  564. try:
  565. img_urls = eval(cell)
  566. self.write_images_to_cell(access_token, doctoken, sheetid, img_urls, row, col_index, compress_image, grid_width, grid_height, border_width, border_color)
  567. except Exception as e:
  568. print(f"写入图片列表失败 (第{row}行第{col_index}列): {e}")
  569. elif is_image_cell(cell):
  570. # 处理单张图片
  571. image_type = get_image_type(cell)
  572. if image_type:
  573. try:
  574. self.write_image_to_cell(access_token, doctoken, sheetid, cell, row, col_index, image_type, compress_image)
  575. except Exception as e:
  576. print(f"写入单张图片失败 (第{row}行第{col_index}列): {e}")
  577. return result
  578. def update_specific_fields(self, access_token, doctoken, sheetid, row, field_updates, headers=None):
  579. """
  580. 只更新指定字段,其他字段保持不变
  581. Args:
  582. access_token: 访问令牌
  583. doctoken: 表格token
  584. sheetid: 工作表ID
  585. row: 目标行号(从1开始)
  586. field_updates: 字段更新字典,格式如 {"列名": "新值", "列B": "新值B"}
  587. 或者 {列索引: "新值", 2: "新值B"}(从1开始计数)
  588. headers: 表头列表,用于列名到列索引的映射。如果为None,则field_updates的key必须是列索引
  589. Returns:
  590. 操作结果
  591. """
  592. try:
  593. # 如果提供了headers且field_updates的key是列名,则转换为列索引
  594. if headers and field_updates:
  595. column_updates = {}
  596. for field_name, value in field_updates.items():
  597. if isinstance(field_name, str): # 如果是列名
  598. try:
  599. col_index = headers.index(field_name) + 1 # 转为1基索引
  600. column_updates[col_index] = value
  601. except ValueError:
  602. print(f"警告:找不到列名 '{field_name}',跳过更新")
  603. continue
  604. else: # 如果已经是列索引
  605. column_updates[field_name] = value
  606. else:
  607. column_updates = field_updates
  608. # 构建批量更新请求
  609. value_ranges = []
  610. for col_index, value in column_updates.items():
  611. col_letter = column_id(col_index)
  612. range_val = f"{sheetid}!{col_letter}{row}:{col_letter}{row}"
  613. value_ranges.append({
  614. "range": range_val,
  615. "values": [[value]]
  616. })
  617. body = {
  618. "valueRanges": value_ranges
  619. }
  620. result = self.batch_update_values(access_token, doctoken, body)
  621. if result:
  622. updated_fields = list(column_updates.keys())
  623. print(f"成功更新第{row}行的字段: {updated_fields}")
  624. return result
  625. except Exception as e:
  626. print(f"更新第{row}行指定字段失败: {e}")
  627. return None
  628. def update_row_with_specific_fields_and_images(self, access_token, doctoken, sheetid, row, field_updates, headers=None, compress_image=True, grid_width=None, grid_height=None, border_width=3, border_color=(200, 200, 200)):
  629. """
  630. 更新指定字段并处理图片
  631. Args:
  632. access_token: 访问令牌
  633. doctoken: 表格token
  634. sheetid: 工作表ID
  635. row: 目标行号
  636. field_updates: 字段更新字典
  637. headers: 表头列表
  638. compress_image: 是否压缩图片
  639. grid_width: 拼接图片的列数
  640. grid_height: 拼接图片的行数
  641. border_width: 边框宽度
  642. border_color: 边框颜色
  643. Returns:
  644. 操作结果
  645. """
  646. # 1. 先更新文本数据
  647. result = self.update_specific_fields(access_token, doctoken, sheetid, row, field_updates, headers)
  648. if not result:
  649. return None
  650. # 2. 处理图片写入
  651. column_updates = {}
  652. if headers and field_updates:
  653. for field_name, value in field_updates.items():
  654. if isinstance(field_name, str): # 如果是列名
  655. try:
  656. col_index = headers.index(field_name) + 1
  657. column_updates[col_index] = value
  658. except ValueError:
  659. continue
  660. else: # 如果已经是列索引
  661. column_updates[field_name] = value
  662. else:
  663. column_updates = field_updates
  664. for col_index, cell in column_updates.items():
  665. if is_image_list_cell_url(cell):
  666. # 处理图片列表
  667. try:
  668. img_urls = eval(cell)
  669. self.write_images_to_cell(access_token, doctoken, sheetid, img_urls, row, col_index, compress_image, grid_width, grid_height, border_width, border_color)
  670. except Exception as e:
  671. print(f"写入图片列表失败 (第{row}行第{col_index}列): {e}")
  672. elif is_image_cell(cell):
  673. # 处理单张图片
  674. image_type = get_image_type(cell)
  675. if image_type:
  676. try:
  677. self.write_image_to_cell(access_token, doctoken, sheetid, cell, row, col_index, image_type, compress_image)
  678. except Exception as e:
  679. print(f"写入单张图片失败 (第{row}行第{col_index}列): {e}")
  680. return result
  681. def insert_row_with_data_at_position(self, access_token, doctoken, sheetid, row_position, values, compress_image=True, grid_width=None, grid_height=None, border_width=3, border_color=(200, 200, 200)):
  682. """
  683. 在指定位置真正插入新行并填入数据
  684. Args:
  685. access_token: 访问令牌
  686. doctoken: 表格token
  687. sheetid: 工作表ID
  688. row_position: 插入位置(从1开始,在此行前插入)
  689. values: 要插入的数据
  690. compress_image: 是否压缩图片
  691. grid_width: 拼接图片的列数
  692. grid_height: 拼接图片的行数
  693. border_width: 边框宽度
  694. border_color: 边框颜色
  695. Returns:
  696. 操作结果
  697. """
  698. # 获取当前工作表行数
  699. sheet_props = self.get_sheet_properties(access_token, doctoken, sheetid)
  700. current_row_count = sheet_props['row_count'] if sheet_props else 1
  701. # 1. 先插入空行
  702. insert_result = self.insert_rows_before(access_token, doctoken, sheetid, row_position, 1)
  703. if not insert_result:
  704. print(f"插入空行失败,无法在第{row_position}行插入数据")
  705. return None
  706. # 如果是追加模式(插入位置超过了原有行数),实际数据位置是当前行数+1
  707. actual_row_position = row_position
  708. if row_position > current_row_count:
  709. actual_row_position = current_row_count + 1
  710. print(f"追加模式:实际数据插入位置调整为第{actual_row_position}行")
  711. # 2. 再在新插入的行中填入数据
  712. result = self.insert_data_at_row(access_token, doctoken, sheetid, actual_row_position, values)
  713. if not result:
  714. print(f"插入数据失败")
  715. return None
  716. # 3. 同时处理图片写入
  717. if values and len(values) > 0:
  718. row_data = values[0]
  719. for col_index, cell in enumerate(row_data, start=1):
  720. if is_image_list_cell_url(cell):
  721. # 处理图片列表
  722. try:
  723. img_urls = eval(cell)
  724. self.write_images_to_cell(access_token, doctoken, sheetid, img_urls, actual_row_position, col_index, compress_image, grid_width, grid_height, border_width, border_color)
  725. except Exception as e:
  726. print(f"写入图片列表失败 (第{actual_row_position}行第{col_index}列): {e}")
  727. elif is_image_cell(cell):
  728. # 处理单张图片
  729. image_type = get_image_type(cell)
  730. if image_type:
  731. try:
  732. self.write_image_to_cell(access_token, doctoken, sheetid, cell, actual_row_position, col_index, image_type, compress_image)
  733. except Exception as e:
  734. print(f"写入单张图片失败 (第{actual_row_position}行第{col_index}列): {e}")
  735. return result
  736. def get_sheet_info(self, access_token, doctoken, sheetid):
  737. """
  738. 获取工作表的基础信息
  739. Args:
  740. access_token: 访问令牌
  741. doctoken: 表格token
  742. sheetid: 工作表ID
  743. Returns:
  744. 工作表信息,包含行数、列数等
  745. """
  746. url = f"{self._host}/open-apis/sheets/v3/spreadsheets/{doctoken}/sheets/{sheetid}"
  747. headers = {
  748. 'Content-Type': 'application/json; charset=utf-8',
  749. 'Authorization': f'Bearer {access_token}'
  750. }
  751. try:
  752. resp = request("GET", url, headers)
  753. return resp['data']['sheet']
  754. except Exception as e:
  755. print(f"获取工作表信息失败: {e}")
  756. return None
  757. def get_sheet_properties(self, access_token, doctoken, sheetid):
  758. """
  759. 获取工作表属性,包括行数和列数
  760. Args:
  761. access_token: 访问令牌
  762. doctoken: 表格token
  763. sheetid: 工作表ID
  764. Returns:
  765. dict: 包含 row_count, column_count 等信息
  766. """
  767. sheet_info = self.get_sheet_info(access_token, doctoken, sheetid)
  768. if sheet_info:
  769. grid_properties = sheet_info.get('grid_properties', {})
  770. return {
  771. 'row_count': grid_properties.get('row_count', 0),
  772. 'column_count': grid_properties.get('column_count', 0),
  773. 'title': sheet_info.get('title', ''),
  774. 'sheet_id': sheet_info.get('sheet_id', ''),
  775. 'sheet_type': sheet_info.get('sheet_type', '')
  776. }
  777. return None
  778. def append_data(self, access_token, doctoken, range_val, values):
  779. """
  780. 在指定位置后面追加数据
  781. Args:
  782. access_token: 访问令牌
  783. doctoken: 表格token
  784. range_val: 追加范围,格式如 "Sheet1!A1:C1"
  785. values: 要追加的数据
  786. Returns:
  787. 操作结果
  788. """
  789. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/values_append"
  790. headers = {
  791. 'Content-Type': 'application/json; charset=utf-8',
  792. 'Authorization': f'Bearer {access_token}'
  793. }
  794. payload = {
  795. "valueRange": {
  796. "range": range_val,
  797. "values": values
  798. }
  799. }
  800. try:
  801. resp = request("POST", url, headers, payload)
  802. return resp
  803. except Exception as e:
  804. print(f"追加数据失败: {e}")
  805. return None
  806. def delete_rows(self, access_token, doctoken, sheetid, start_row, end_row):
  807. """
  808. 删除指定范围的行
  809. Args:
  810. access_token: 访问令牌
  811. doctoken: 表格token
  812. sheetid: 工作表ID
  813. start_row: 开始行号(从1开始)
  814. end_row: 结束行号(从1开始,包含)
  815. Returns:
  816. 操作结果
  817. """
  818. url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{doctoken}/dimension_range"
  819. headers = {
  820. 'Content-Type': 'application/json; charset=utf-8',
  821. 'Authorization': f'Bearer {access_token}'
  822. }
  823. payload = {
  824. "dimension": {
  825. "sheetId": sheetid,
  826. "majorDimension": "ROWS",
  827. "startIndex": start_row, # 从1开始计数,包含
  828. "endIndex": end_row # 从1开始计数,包含
  829. }
  830. }
  831. try:
  832. resp = request("DELETE", url, headers, payload)
  833. return resp
  834. except Exception as e:
  835. print(f"删除第{start_row}-{end_row}行失败: {e}")
  836. return None
  837. def delete_single_row(self, access_token, doctoken, sheetid, row):
  838. """
  839. 删除单行
  840. Args:
  841. access_token: 访问令牌
  842. doctoken: 表格token
  843. sheetid: 工作表ID
  844. row: 行号(从1开始)
  845. Returns:
  846. 操作结果
  847. """
  848. return self.delete_rows(access_token, doctoken, sheetid, row, row)
  849. def append_empty_rows(self, access_token, doctoken, sheetid, count=1):
  850. """
  851. 在工作表末尾追加空行
  852. Args:
  853. access_token: 访问令牌
  854. doctoken: 表格token
  855. sheetid: 工作表ID
  856. count: 追加行数(默认1行)
  857. Returns:
  858. 操作结果
  859. """
  860. # 获取当前工作表信息
  861. sheet_props = self.get_sheet_properties(access_token, doctoken, sheetid)
  862. if not sheet_props:
  863. print("无法获取工作表信息,追加失败")
  864. return None
  865. current_row_count = sheet_props['row_count']
  866. current_col_count = sheet_props['column_count']
  867. print(f"在工作表末尾追加{count}行,当前行数: {current_row_count}")
  868. # 构造空数据行
  869. empty_values = [[''] * max(current_col_count, 1) for _ in range(count)]
  870. # 使用append_data在末尾追加
  871. range_val = f"{sheetid}!A{current_row_count + 1}:{column_id(max(current_col_count, 1))}{current_row_count + count}"
  872. try:
  873. result = self.append_data(access_token, doctoken, range_val, empty_values)
  874. if result:
  875. print(f"成功在末尾追加{count}行空行")
  876. return result
  877. except Exception as e:
  878. print(f"追加空行失败: {e}")
  879. return None
  880. # -*- coding: UTF-8 -*-
  881. import json
  882. import logging
  883. from datetime import datetime
  884. import re
  885. import os
  886. import requests
  887. from urllib.parse import urlparse
  888. LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
  889. logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)
  890. import os
  891. logging.info(os.getcwd())
  892. def column_id(col):
  893. '''column int to string id'''
  894. ans = ""
  895. i = col
  896. while i > 0:
  897. m = int((i-1) % 26)
  898. i = int((i-1) / 26)
  899. ans = chr(m+65) + ans
  900. return ans
  901. def get_image_type(url):
  902. '''根据图片URL获取图片类型'''
  903. try:
  904. # 发送 HEAD 请求以获取头信息
  905. path = urlparse(url).path
  906. ext = path.split('.')[-1].lower()
  907. if ext in ['jpg', 'jpeg', 'png', 'gif']:
  908. return ext
  909. ext = 'jpeg'
  910. if 'jpg' in url:
  911. ext = 'jpg'
  912. if 'jpeg' in url:
  913. ext = 'jpeg'
  914. if 'png' in url:
  915. ext = 'png'
  916. if 'gif' in url:
  917. ext = 'gif'
  918. if "webp" in url:
  919. ext = "webp"
  920. # 如果无法确定类型,返回 None
  921. return ext
  922. except Exception as e:
  923. print(f"获取图片类型时出错: {str(e)}")
  924. return None
  925. def is_image_cell(cell):
  926. # 判断是否包含中文字符
  927. if isinstance(cell, str):
  928. for char in cell:
  929. if '\u4e00' <= char <= '\u9fff':
  930. return False
  931. is_image = False
  932. if (
  933. isinstance(cell, str) and
  934. cell.startswith('http') and
  935. (
  936. re.match(r'https?://.+\.(jpg|jpeg|png|gif|webp).*', cell, re.I) or re.match(r'http?://.+\.(jpg|jpeg|png|gif|webp).*', cell, re.I) or
  937. ('xhscdn.com' in cell and 'format/jpg' in cell) or
  938. ('rescdn.yishihui.com' in cell and 'jpg' in cell) or
  939. 'sns-webpic-qc.xhscdn.com' in cell or 'ci.xiaohongshu.com' in cell
  940. )
  941. ):
  942. is_image = True
  943. return is_image
  944. def is_image_list_cell_url(cell):
  945. if isinstance(cell, str) and cell.strip() and cell[0] == '[' and cell[-1] == ']':
  946. try:
  947. cell_obj = eval(cell)
  948. except:
  949. return False
  950. if type(cell_obj) == list:
  951. for c in cell_obj:
  952. if not is_image_cell(c):
  953. return False
  954. return True
  955. return False
  956. def write_images(client, access_token, token, sheetid, data, start_row=1, start_col=1, skip_col=[], compress_image=True, grid_width=None, grid_height=None, border_width=3, border_color=(200, 200, 200)):
  957. '''将图片URL写入单元格'''
  958. for row_index, row in enumerate(data, start=1):
  959. if row_index < start_row:
  960. print(f"跳过行: {row_index}")
  961. continue
  962. for col_index, cell in enumerate(row, start=1):
  963. # if cell is not None and "http" in cell and is_image_cell(cell) is False:
  964. # print(f"is_image_cell = {is_image_cell(cell)}, {cell}")
  965. if col_index < start_col:
  966. continue
  967. if col_index in skip_col:
  968. continue
  969. if is_image_list_cell_url(cell):
  970. # print(f"is_image_list_cell_url = True , {cell}")
  971. client.write_images_to_cell(access_token, token, sheetid, eval(cell), row_index, col_index, compress_image, grid_width, grid_height, border_width, border_color)
  972. elif is_image_cell(cell):
  973. image_type = get_image_type(cell)
  974. if image_type:
  975. client.write_image_to_cell(access_token, token, sheetid, cell, row_index, col_index,image_type, compress_image)
  976. def merge_cells(client, access_token, token, sheetid, data ):
  977. row_cnt = len(data)
  978. col_cnt = len(data[0])
  979. for col in range(0,col_cnt):
  980. previous_row = 0
  981. previous_value = None
  982. for row in range(0,row_cnt):
  983. cell_value = data[row][col]
  984. if cell_value != previous_value :
  985. if row - previous_row > 1:
  986. client.merge_cells(access_token, token, sheetid, previous_row+1, row, col+1, col+1)
  987. previous_row = row
  988. previous_value= cell_value
  989. def pack_data(data, sheetid, start_row=1, start_col=1):
  990. rows = len(data)
  991. cols = len(data[0])
  992. range1 = f"{sheetid}!{column_id(start_col)}{start_row}:{column_id(cols)}{rows}"
  993. body = {
  994. "valueRanges": [
  995. {
  996. "range": range1,
  997. "values": []
  998. },
  999. ]
  1000. }
  1001. print(range1)
  1002. for d in data[start_row-1:]:
  1003. row = []
  1004. for c in d[start_col-1:]:
  1005. row.append(c)
  1006. body["valueRanges"][0]["values"].append(row)
  1007. return body
  1008. def write_data_to_sheet(data, sheet_token='IoTOsjZ4khIqlOtTxnec8oTbn7c', sheetid=None, skip_text=False, skip_images=False, start_row=1, start_col=1, skip_col=[], compress_image=True, grid_width=None, grid_height=None, border_width=3, border_color=(200, 200, 200)):
  1009. '''测试函数'''
  1010. # 初始化 API 客户端
  1011. client = Client(LARK_HOST)
  1012. # 获取租户访问令牌
  1013. access_token = client.get_tenant_access_token(APP_ID, APP_SECRET)
  1014. # 获取第一个 sheet_id
  1015. if sheetid is None:
  1016. sheetid = client.get_sheetid(access_token, sheet_token)
  1017. print(f"Sheet ID: {sheetid}")
  1018. # 构建并写入测试数据
  1019. body = pack_data(data,
  1020. sheetid, start_row=start_row, start_col=start_col)
  1021. if not skip_text:
  1022. client.batch_update_values(access_token, sheet_token, body)
  1023. # merge_cells(client, access_token, sheet_token, sheetid, data)
  1024. # 写入图片
  1025. if not skip_images:
  1026. write_images(client, access_token, sheet_token, sheetid, data, start_row=start_row, start_col=start_col, skip_col=skip_col, compress_image=compress_image, grid_width=grid_width, grid_height=grid_height, border_width=border_width, border_color=border_color)
  1027. def get_test_data():
  1028. data = [
  1029. ["标题1", "标题2", "标题3", "图片"],
  1030. [1, 2,2, "http://sns-webpic.xhscdn.com/1040g2sg316vc6tdrk4705o8h0c2095f1else4i8?imageView2/2/w/0/format/jpg/v3"],
  1031. [4, "https://cdn.midjourney.com/f78df4d5-9b8b-4ec7-ae34-5cc04d176f87/0_0.png", 6, "dd"],
  1032. # [7, 8, 9, "https://sns-webpic.xhscdn.com/1040g2sg317l7814ck4705n3aa5ik4jgjahhcam0?imageView2/2/w/0/format/jpg/v3"],
  1033. ]
  1034. return data
  1035. from typing import List, Dict
  1036. import pandas as pd
  1037. import json
  1038. def to_feishu(
  1039. res_list: List[Dict],
  1040. sheet_id: str = 'Qn9MAs',
  1041. sheet_token: str = 'Rbsysi6FChzCp7tfv19crkWNnEb',
  1042. start_row: int = 1,
  1043. start_col: int = 1,
  1044. grid_width: int = None,
  1045. grid_height: int = None,
  1046. border_width: int = 3,
  1047. border_color: tuple = (200, 200, 200),
  1048. ) -> None:
  1049. """
  1050. 将数据导出到飞书表格
  1051. Args:
  1052. res_list: 数据列表
  1053. sheet_id: 表格ID
  1054. sheet_token: 表格token
  1055. start_row: 起始行
  1056. start_col: 起始列
  1057. grid_width: 拼接图片的列数,如果为None则自动计算
  1058. grid_height: 拼接图片的行数,如果为None则自动计算
  1059. border_width: 边框宽度,像素
  1060. border_color: 边框颜色,RGB元组
  1061. """
  1062. from tqdm import tqdm
  1063. def truncate_by_bytes(text, max_bytes=450000):
  1064. """按字节长度截断文本"""
  1065. if not text:
  1066. return ""
  1067. text_str = str(text)
  1068. encoded = text_str.encode('utf-8')
  1069. if len(encoded) <= max_bytes:
  1070. return text_str
  1071. # 安全截断,避免截断多字节字符
  1072. truncated = encoded[:max_bytes]
  1073. while len(truncated) > 0:
  1074. try:
  1075. return truncated.decode('utf-8') + "...[已截断]"
  1076. except UnicodeDecodeError:
  1077. truncated = truncated[:-1]
  1078. return ""
  1079. res_new_v4 = []
  1080. for row in tqdm(res_list):
  1081. if not row:
  1082. continue
  1083. for k, v in row.items():
  1084. if isinstance(v, list):
  1085. if len(v) > 0 and v[0] and v[0].startswith('http'):
  1086. row[k] = truncate_by_bytes(str(v))
  1087. else:
  1088. json_str = json.dumps(v, ensure_ascii=False, separators=(',', ':'))
  1089. row[k] = truncate_by_bytes(json_str)
  1090. elif isinstance(v, dict):
  1091. json_str = json.dumps(v, ensure_ascii=False, indent=2)
  1092. row[k] = truncate_by_bytes(json_str)
  1093. else:
  1094. row[k] = truncate_by_bytes(v)
  1095. res_new_v4.append(row)
  1096. df = pd.DataFrame(res_new_v4)
  1097. df.fillna('', inplace=True)
  1098. header = df.columns.tolist()
  1099. data_rows = df.values.tolist()
  1100. data_with_header = [header] + data_rows
  1101. write_data_to_sheet(
  1102. data_with_header,
  1103. sheet_token=sheet_token,
  1104. sheetid=sheet_id,
  1105. start_col=start_col,
  1106. start_row=start_row,
  1107. grid_width=grid_width,
  1108. grid_height=grid_height,
  1109. border_width=border_width,
  1110. border_color=border_color,
  1111. )
  1112. def to_feishu_incremental(
  1113. res_list: List[Dict],
  1114. sort_field: str = '内容ID',
  1115. sheet_id: str = 'Qn9MAs',
  1116. sheet_token: str = 'Rbsysi6FChzCp7tfv19crkWNnEb',
  1117. unique_field: str = None, # 用于去重的唯一字段,默认使用sort_field
  1118. duplicate_strategy: str = 'skip', # 重复数据处理策略:'skip'跳过, 'delete'删除后插入, 'update'更新
  1119. update_fields: List[str] = None, # 当duplicate_strategy='update'时,指定要更新的字段列表。None表示更新所有字段
  1120. cleanup_duplicates: bool = True, # 是否先清理现有表格中的重复数据
  1121. keep_first: bool = True, # 清理重复数据时保留第一个(True)还是最后一个(False)
  1122. sort_ascending: bool = False, # 排序顺序:True为升序(从小到大),False为降序(从大到小)
  1123. grid_width: int = None,
  1124. grid_height: int = None,
  1125. border_width: int = 3,
  1126. border_color: tuple = (200, 200, 200),
  1127. ) -> None:
  1128. """
  1129. 逐行增量插入数据到飞书表格,按指定字段查找插入位置
  1130. Args:
  1131. res_list: 数据列表
  1132. sort_field: 用于排序的字段名,如 '内容ID'
  1133. sheet_id: 表格ID
  1134. sheet_token: 表格token
  1135. unique_field: 用于去重的唯一字段,默认使用sort_field
  1136. duplicate_strategy: 重复数据处理策略
  1137. - 'skip': 跳过重复数据(默认)
  1138. - 'delete': 删除重复数据后插入新数据
  1139. - 'update': 更新重复数据的指定字段
  1140. update_fields: 当duplicate_strategy='update'时,指定要更新的字段列表
  1141. - None: 更新所有字段(除了unique_field)
  1142. - ['字段1', '字段2']: 只更新指定的字段
  1143. cleanup_duplicates: 是否先清理现有表格中的重复数据
  1144. keep_first: 清理重复数据时保留第一个(True)还是最后一个(False)
  1145. sort_ascending: 排序顺序,True为升序(从小到大),False为降序(从大到小),默认False
  1146. grid_width: 拼接图片的列数,如果为None则自动计算
  1147. grid_height: 拼接图片的行数,如果为None则自动计算
  1148. border_width: 边框宽度,像素
  1149. border_color: 边框颜色,RGB元组
  1150. """
  1151. from tqdm import tqdm
  1152. import pandas as pd
  1153. import json
  1154. from typing import List
  1155. def truncate_by_bytes(text, max_bytes=450000):
  1156. """按字节长度截断文本"""
  1157. if not text:
  1158. return ""
  1159. text_str = str(text)
  1160. encoded = text_str.encode('utf-8')
  1161. if len(encoded) <= max_bytes:
  1162. return text_str
  1163. # 安全截断,避免截断多字节字符
  1164. truncated = encoded[:max_bytes]
  1165. while len(truncated) > 0:
  1166. try:
  1167. return truncated.decode('utf-8') + "...[已截断]"
  1168. except UnicodeDecodeError:
  1169. truncated = truncated[:-1]
  1170. return ""
  1171. # 初始化 API 客户端
  1172. client = Client(LARK_HOST)
  1173. access_token = client.get_tenant_access_token(APP_ID, APP_SECRET)
  1174. # 设置去重字段,默认使用排序字段
  1175. if unique_field is None:
  1176. unique_field = sort_field
  1177. # 1. 获取工作表基础信息
  1178. print("正在获取工作表信息...")
  1179. sheet_props = client.get_sheet_properties(access_token, sheet_token, sheet_id)
  1180. if not sheet_props:
  1181. print("获取工作表信息失败,使用默认范围")
  1182. max_col = 'ZZ'
  1183. max_row = 1000
  1184. else:
  1185. print(f"工作表信息: 行数={sheet_props['row_count']}, 列数={sheet_props['column_count']}")
  1186. max_col = column_id(sheet_props['column_count']) if sheet_props['column_count'] > 0 else 'ZZ'
  1187. max_row = sheet_props['row_count'] if sheet_props['row_count'] > 0 else 1000
  1188. # 2. 读取表头(使用精确范围)
  1189. print("正在读取表头...")
  1190. header_range = f"{sheet_id}!A1:{max_col}1" # 表头总是从A列开始读取
  1191. header_data = client.read_range_values(access_token, sheet_token, header_range)
  1192. if not header_data or not header_data[0] or all(not cell.strip() for cell in header_data[0] if cell):
  1193. print("表格为空,需要根据数据创建表头")
  1194. # 从第一条数据中提取字段名作为表头
  1195. if not res_list or not res_list[0]:
  1196. print("错误:无法从空数据中创建表头")
  1197. return
  1198. # 提取字段名
  1199. headers = list(res_list[0].keys())
  1200. print(f"创建表头: {headers}")
  1201. # 写入表头(表头不包含图片,使用普通插入即可)
  1202. header_range = f"{sheet_id}!A1:{column_id(len(headers))}1"
  1203. client.insert_data_at_row(access_token, sheet_token, sheet_id, 1, [headers])
  1204. # 表头创建后,从第二行开始插入数据
  1205. print("表头创建完成,开始插入数据...")
  1206. else:
  1207. # 解析现有表头
  1208. headers = [cell.strip() for cell in header_data[0] if cell is not None]
  1209. headers = [h for h in headers if h] # 移除空字段
  1210. print(f"读取到现有表头: {headers}")
  1211. # 检查排序字段和去重字段是否存在
  1212. if sort_field not in headers:
  1213. print(f"警告: 排序字段 '{sort_field}' 未在表头中找到。可用字段: {headers}")
  1214. # 如果找不到排序字段,就直接追加到末尾
  1215. # 使用工作表信息中的行数,或从第二行开始(如果刚创建了表头)
  1216. start_row = len(headers) + 1 if 'headers' in locals() else (max_row + 1 if sheet_props else 2)
  1217. to_feishu(res_list, sheet_id, sheet_token, start_row, 1, grid_width, grid_height, border_width, border_color)
  1218. return
  1219. if unique_field not in headers:
  1220. print(f"警告: 去重字段 '{unique_field}' 未在表头中找到,将使用排序字段 '{sort_field}' 进行去重")
  1221. unique_field = sort_field
  1222. sort_field_index = headers.index(sort_field)
  1223. sort_field_col = column_id(sort_field_index + 1) # 转换为列标识符,如A, B, C...
  1224. unique_field_index = headers.index(unique_field)
  1225. unique_field_col = column_id(unique_field_index + 1) # 转换为列标识符,如A, B, C...
  1226. # 3. 读取排序字段和去重字段的数据
  1227. print(f"正在读取排序字段 '{sort_field}' 和去重字段 '{unique_field}' 列数据...")
  1228. # 读取排序字段数据
  1229. sort_data_range = f"{sheet_id}!{sort_field_col}2:{sort_field_col}{max_row}"
  1230. all_sort_data = client.read_range_values(access_token, sheet_token, sort_data_range)
  1231. # 读取去重字段数据(如果与排序字段不同)
  1232. if unique_field != sort_field:
  1233. unique_data_range = f"{sheet_id}!{unique_field_col}2:{unique_field_col}{max_row}"
  1234. all_unique_data = client.read_range_values(access_token, sheet_token, unique_data_range)
  1235. else:
  1236. all_unique_data = all_sort_data
  1237. # 先清理空白行(排序字段和去重字段都为空的行)
  1238. print("检查并清理空白行...")
  1239. empty_rows_to_delete = []
  1240. if all_unique_data and all_sort_data:
  1241. for i in range(min(len(all_unique_data), len(all_sort_data))):
  1242. unique_row = all_unique_data[i] if i < len(all_unique_data) else None
  1243. sort_row = all_sort_data[i] if i < len(all_sort_data) else None
  1244. # 检查去重字段值
  1245. unique_value = ""
  1246. if unique_row and len(unique_row) > 0 and unique_row[0]:
  1247. unique_value = str(unique_row[0]).strip()
  1248. # 检查排序字段值
  1249. sort_value = ""
  1250. if sort_row and len(sort_row) > 0 and sort_row[0]:
  1251. sort_value = str(sort_row[0]).strip()
  1252. # 如果排序字段和去重字段都为空,标记为空白行
  1253. if not unique_value and not sort_value:
  1254. row_number = i + 2 # +2 因为从第2行开始,且行号从1开始
  1255. empty_rows_to_delete.append(row_number)
  1256. print(f"标记删除空白行: 第{row_number}行")
  1257. # 删除空白行
  1258. if empty_rows_to_delete:
  1259. print(f"开始删除 {len(empty_rows_to_delete)} 个空白行...")
  1260. # 按行号倒序删除,避免删除后行号变化的问题
  1261. empty_rows_to_delete.sort(reverse=True)
  1262. for row_to_delete in empty_rows_to_delete:
  1263. delete_result = client.delete_single_row(access_token, sheet_token, sheet_id, row_to_delete)
  1264. if delete_result:
  1265. print(f"成功删除空白行: 第{row_to_delete}行")
  1266. else:
  1267. print(f"删除空白行失败: 第{row_to_delete}行")
  1268. # 重新读取数据(删除后数据已经改变)
  1269. print("重新读取数据(清理空白行后)...")
  1270. # 重新读取排序字段数据
  1271. sort_data_range = f"{sheet_id}!{sort_field_col}2:{sort_field_col}{max_row}"
  1272. all_sort_data = client.read_range_values(access_token, sheet_token, sort_data_range)
  1273. # 重新读取去重字段数据
  1274. if unique_field != sort_field:
  1275. unique_data_range = f"{sheet_id}!{unique_field_col}2:{unique_field_col}{max_row}"
  1276. all_unique_data = client.read_range_values(access_token, sheet_token, unique_data_range)
  1277. else:
  1278. all_unique_data = all_sort_data
  1279. # 构建现有数据的去重集合
  1280. duplicate_rows_to_delete = []
  1281. if cleanup_duplicates and all_unique_data:
  1282. # 先分析重复数据
  1283. seen_unique_values = {} # 记录已见过的唯一值和对应行号
  1284. actual_data_rows = [] # 记录实际有数据的行号
  1285. print(f"开始分析重复数据,总共读取了 {len(all_unique_data)} 行数据")
  1286. # 先找出所有有效数据行及其对应的实际行号(必须同时有排序字段和去重字段的值)
  1287. for i in range(min(len(all_unique_data), len(all_sort_data) if all_sort_data else 0)):
  1288. unique_row = all_unique_data[i] if i < len(all_unique_data) else None
  1289. sort_row = all_sort_data[i] if i < len(all_sort_data) else None
  1290. # 检查去重字段值
  1291. unique_value = ""
  1292. if unique_row and len(unique_row) > 0 and unique_row[0]:
  1293. unique_value = str(unique_row[0]).strip()
  1294. # 检查排序字段值
  1295. sort_value = ""
  1296. if sort_row and len(sort_row) > 0 and sort_row[0]:
  1297. sort_value = str(sort_row[0]).strip()
  1298. # 只有当排序字段和去重字段都有值时,才认为是有效数据
  1299. if unique_value and sort_value:
  1300. actual_row_number = i + 2 # +2 因为从第2行开始,且行号从1开始
  1301. actual_data_rows.append((actual_row_number, unique_value, sort_value))
  1302. print(f"找到 {len(actual_data_rows)} 行有效数据")
  1303. # 分析重复数据
  1304. for actual_row_number, unique_value, sort_value in actual_data_rows:
  1305. if unique_value in seen_unique_values:
  1306. # 发现重复数据
  1307. if keep_first:
  1308. # 保留第一个,删除当前这个
  1309. duplicate_rows_to_delete.append(actual_row_number)
  1310. print(f"标记删除重复行: 第{actual_row_number}行 ({unique_field}={unique_value}, {sort_field}={sort_value})")
  1311. else:
  1312. # 保留最后一个,删除之前的
  1313. previous_row = seen_unique_values[unique_value]
  1314. duplicate_rows_to_delete.append(previous_row)
  1315. print(f"标记删除重复行: 第{previous_row}行 ({unique_field}={unique_value}, {sort_field}={sort_value})")
  1316. seen_unique_values[unique_value] = actual_row_number
  1317. else:
  1318. # 第一次见到这个唯一值
  1319. seen_unique_values[unique_value] = actual_row_number
  1320. # 执行清理:删除重复行
  1321. if duplicate_rows_to_delete:
  1322. print(f"开始清理 {len(duplicate_rows_to_delete)} 行重复数据...")
  1323. # 按行号倒序删除,避免删除后行号变化的问题
  1324. duplicate_rows_to_delete.sort(reverse=True)
  1325. for row_to_delete in duplicate_rows_to_delete:
  1326. delete_result = client.delete_single_row(access_token, sheet_token, sheet_id, row_to_delete)
  1327. if delete_result:
  1328. print(f"成功删除重复行: 第{row_to_delete}行")
  1329. else:
  1330. print(f"删除重复行失败: 第{row_to_delete}行")
  1331. # 重新读取数据(删除后数据已经改变)
  1332. print("重新读取排序和去重字段数据...")
  1333. # 重新读取排序字段数据
  1334. sort_data_range = f"{sheet_id}!{sort_field_col}2:{sort_field_col}{max_row}"
  1335. all_sort_data = client.read_range_values(access_token, sheet_token, sort_data_range)
  1336. # 重新读取去重字段数据
  1337. if unique_field != sort_field:
  1338. unique_data_range = f"{sheet_id}!{unique_field_col}2:{unique_field_col}{max_row}"
  1339. all_unique_data = client.read_range_values(access_token, sheet_token, unique_data_range)
  1340. else:
  1341. all_unique_data = all_sort_data
  1342. # 构建最终的去重集合(处理清理后的数据,必须同时有排序字段和去重字段的值)
  1343. existing_unique_values = set()
  1344. existing_unique_rows = {} # 用于update策略:{unique_value: row_number}
  1345. if all_unique_data and all_sort_data:
  1346. for i in range(min(len(all_unique_data), len(all_sort_data))):
  1347. unique_row = all_unique_data[i] if i < len(all_unique_data) else None
  1348. sort_row = all_sort_data[i] if i < len(all_sort_data) else None
  1349. # 检查去重字段值
  1350. unique_value = ""
  1351. if unique_row and len(unique_row) > 0 and unique_row[0]:
  1352. unique_value = str(unique_row[0]).strip()
  1353. # 检查排序字段值
  1354. sort_value = ""
  1355. if sort_row and len(sort_row) > 0 and sort_row[0]:
  1356. sort_value = str(sort_row[0]).strip()
  1357. # 只有当排序字段和去重字段都有值时,才添加到去重集合
  1358. if unique_value and sort_value:
  1359. actual_row_number = i + 2 # +2 因为从第2行开始,且行号从1开始
  1360. existing_unique_values.add(unique_value)
  1361. existing_unique_rows[unique_value] = actual_row_number
  1362. print(f"现有去重值数量: {len(existing_unique_values)}")
  1363. print(existing_unique_values)
  1364. # 获取排序数据用于插入位置计算(基于清理后的最新数据)
  1365. sort_data = []
  1366. if all_sort_data:
  1367. # 同时检查排序字段和去重字段,确保数据完整性
  1368. for i in range(min(len(all_sort_data), len(all_unique_data) if all_unique_data else 0)):
  1369. sort_row = all_sort_data[i] if i < len(all_sort_data) else None
  1370. unique_row = all_unique_data[i] if i < len(all_unique_data) else None
  1371. # 检查排序字段值
  1372. sort_value = ""
  1373. if sort_row and len(sort_row) > 0 and sort_row[0]:
  1374. sort_value = str(sort_row[0]).strip()
  1375. # 检查去重字段值
  1376. unique_value = ""
  1377. if unique_row and len(unique_row) > 0 and unique_row[0]:
  1378. unique_value = str(unique_row[0]).strip()
  1379. # 只有当排序字段和去重字段都有值时,才加入排序数据
  1380. if sort_value and unique_value:
  1381. sort_data.append([sort_value])
  1382. if not sort_data:
  1383. print("未读取到排序字段数据,所有新数据将从第二行开始插入")
  1384. # 处理新数据
  1385. processed_data = []
  1386. for row in tqdm(res_list, desc="处理数据"):
  1387. if not row:
  1388. continue
  1389. processed_row = {}
  1390. for k, v in row.items():
  1391. if isinstance(v, list):
  1392. if len(v) > 0 and v[0] and str(v[0]).startswith('http'):
  1393. processed_row[k] = truncate_by_bytes(str(v))
  1394. else:
  1395. json_str = json.dumps(v, ensure_ascii=False, indent=1)
  1396. processed_row[k] = truncate_by_bytes(json_str)
  1397. elif isinstance(v, dict):
  1398. json_str = json.dumps(v, ensure_ascii=False, indent=1)
  1399. processed_row[k] = truncate_by_bytes(json_str)
  1400. else:
  1401. processed_row[k] = truncate_by_bytes(v)
  1402. processed_data.append(processed_row)
  1403. # 转换为DataFrame以便操作
  1404. df_new = pd.DataFrame(processed_data)
  1405. df_new.fillna('', inplace=True)
  1406. # 确保新数据包含所有必要的列
  1407. for header in headers:
  1408. if header not in df_new.columns:
  1409. df_new[header] = ''
  1410. # 按表头顺序重新排列列
  1411. df_new = df_new.reindex(columns=headers, fill_value='')
  1412. # 预处理:过滤重复数据并确定插入顺序
  1413. print(f"预处理新数据:过滤重复并排序...")
  1414. print(f"传入数据总量: {len(df_new)} 行")
  1415. print(f"现有去重集合大小: {len(existing_unique_values)}")
  1416. valid_rows = []
  1417. update_rows = [] # 需要更新的行:[{row_number, values, unique_value}, ...]
  1418. skipped_count = 0
  1419. new_data_duplicates = 0 # 新数据内部重复计数
  1420. updated_count = 0 # 更新计数
  1421. for idx, new_row in df_new.iterrows():
  1422. new_row_values = new_row.tolist()
  1423. new_sort_value = str(new_row_values[sort_field_index])
  1424. new_unique_value = str(new_row_values[unique_field_index])
  1425. # 检查是否与现有数据重复
  1426. if new_unique_value in existing_unique_values:
  1427. if duplicate_strategy == 'update':
  1428. # 更新策略:记录需要更新的行
  1429. target_row = existing_unique_rows[new_unique_value]
  1430. update_rows.append({
  1431. 'row_number': target_row,
  1432. 'values': new_row_values,
  1433. 'unique_value': new_unique_value
  1434. })
  1435. print(f"标记更新现有数据: 第{target_row}行 {unique_field}={new_unique_value}")
  1436. updated_count += 1
  1437. continue
  1438. elif duplicate_strategy == 'delete':
  1439. # 删除策略:先删除现有行,再插入新数据
  1440. target_row = existing_unique_rows[new_unique_value]
  1441. delete_result = client.delete_single_row(access_token, sheet_token, sheet_id, target_row)
  1442. if delete_result:
  1443. print(f"成功删除重复行: 第{target_row}行 {unique_field}={new_unique_value}")
  1444. # 从去重集合中移除,允许后续插入
  1445. existing_unique_values.remove(new_unique_value)
  1446. # 更新所有行号(删除后后面的行号会前移)
  1447. for key, row_num in existing_unique_rows.items():
  1448. if row_num > target_row:
  1449. existing_unique_rows[key] = row_num - 1
  1450. del existing_unique_rows[new_unique_value]
  1451. else:
  1452. print(f"删除重复行失败: 第{target_row}行 {unique_field}={new_unique_value}")
  1453. skipped_count += 1
  1454. continue
  1455. else: # 'skip' 策略
  1456. print(f"跳过与现有数据重复: {unique_field}={new_unique_value}")
  1457. skipped_count += 1
  1458. continue
  1459. # 检查新数据内部是否重复
  1460. already_processed = any(row['unique_value'] == new_unique_value for row in valid_rows)
  1461. if already_processed:
  1462. print(f"跳过新数据内部重复: {unique_field}={new_unique_value}")
  1463. new_data_duplicates += 1
  1464. continue
  1465. # 添加到待插入列表
  1466. valid_rows.append({
  1467. 'values': new_row_values,
  1468. 'sort_value': new_sort_value,
  1469. 'unique_value': new_unique_value
  1470. })
  1471. print(f"预处理完成:有效数据 {len(valid_rows)} 行,需要更新 {len(update_rows)} 行,跳过与现有重复 {skipped_count} 行,跳过新数据内部重复 {new_data_duplicates} 行")
  1472. # 处理更新操作
  1473. if update_rows:
  1474. print(f"开始执行更新操作,共 {len(update_rows)} 行...")
  1475. for update_data in tqdm(update_rows, desc="更新数据"):
  1476. row_number = update_data['row_number']
  1477. new_values = update_data['values']
  1478. unique_value = update_data['unique_value']
  1479. # 构建字段更新字典
  1480. if update_fields is None:
  1481. # 更新所有字段,但排除unique_field(避免修改关键字段)
  1482. field_updates = {}
  1483. for i, header in enumerate(headers):
  1484. if header != unique_field: # 不更新去重字段
  1485. field_updates[header] = new_values[i]
  1486. print(f"更新第{row_number}行所有字段(除了{unique_field}): {unique_value}")
  1487. else:
  1488. # 只更新指定字段
  1489. field_updates = {}
  1490. for field_name in update_fields:
  1491. if field_name in headers:
  1492. field_index = headers.index(field_name)
  1493. field_updates[field_name] = new_values[field_index]
  1494. else:
  1495. print(f"警告:字段 '{field_name}' 不存在于表头中,跳过")
  1496. print(f"更新第{row_number}行指定字段 {list(field_updates.keys())}: {unique_value}")
  1497. # 执行更新
  1498. if field_updates:
  1499. result = client.update_row_with_specific_fields_and_images(
  1500. access_token, sheet_token, sheet_id, row_number,
  1501. field_updates, headers, True, grid_width, grid_height, border_width, border_color
  1502. )
  1503. if result:
  1504. print(f"✅ 成功更新第{row_number}行")
  1505. else:
  1506. print(f"❌ 更新第{row_number}行失败")
  1507. if not valid_rows:
  1508. if update_rows:
  1509. print("所有数据均为更新操作,无新数据需要插入")
  1510. else:
  1511. print("没有新数据需要插入")
  1512. return
  1513. # 按排序字段排序新数据(根据sort_ascending参数决定排序方向)
  1514. if sort_ascending:
  1515. # 升序排序:小的值先插入(reverse=False)
  1516. valid_rows.sort(key=lambda x: x['sort_value'], reverse=False)
  1517. print(f"新数据排序完成,将按升序插入")
  1518. else:
  1519. # 降序排序:大的值先插入(reverse=True)
  1520. valid_rows.sort(key=lambda x: x['sort_value'], reverse=True)
  1521. print(f"新数据排序完成,将按降序插入")
  1522. # 逐行插入已排序的数据
  1523. for i, row_data in tqdm(enumerate(valid_rows), total=len(valid_rows), desc="插入数据"):
  1524. new_row_values = row_data['values']
  1525. new_sort_value = row_data['sort_value']
  1526. new_unique_value = row_data['unique_value']
  1527. # 找到合适的插入位置(根据sort_ascending参数确定排序方向)
  1528. insert_row = len(sort_data) + 2 # 默认插入到末尾
  1529. print(f"查找插入位置,新值: {new_sort_value}")
  1530. # 找到两个相邻ID之间的正确插入位置
  1531. if sort_ascending:
  1532. # 升序排列:小 → 大,需要找到 prev_value < new_value < current_value 的位置
  1533. for j in range(len(sort_data)):
  1534. current_value = str(sort_data[j][0]) if sort_data[j] and len(sort_data[j]) > 0 else ""
  1535. prev_value = str(sort_data[j-1][0]) if j > 0 and sort_data[j-1] and len(sort_data[j-1]) > 0 else None
  1536. # 检查是否应该插入到当前位置
  1537. if prev_value is None:
  1538. # 这是第一个位置,检查是否应该插入到最前面
  1539. if new_sort_value < current_value:
  1540. insert_row = j + 2 # +2 因为表头偏移
  1541. print(f" 插入到最前面第{insert_row}行: 新值{new_sort_value} < 第一个值{current_value}")
  1542. break
  1543. else:
  1544. # 检查是否在两个相邻值之间
  1545. if new_sort_value >= prev_value and new_sort_value < current_value:
  1546. insert_row = j + 2 # +2 因为表头偏移
  1547. print(f" 插入到第{insert_row}行: {prev_value} <= {new_sort_value} < {current_value}")
  1548. break
  1549. elif new_sort_value == current_value:
  1550. # 值相等时插入到相等值之后
  1551. insert_row = j + 3 # +2(表头偏移) +1(插入到此行之后)
  1552. print(f" 插入到第{insert_row}行: 新值{new_sort_value} = 现有值{current_value},插入其后")
  1553. break
  1554. # 如果遍历完都没有找到位置,说明新值是最大的,插入到末尾
  1555. if insert_row == len(sort_data) + 2:
  1556. last_value = str(sort_data[-1][0]) if sort_data and sort_data[-1] and len(sort_data[-1]) > 0 else "无"
  1557. print(f" 插入到末尾第{insert_row}行: 新值{new_sort_value} > 最后一个值{last_value}")
  1558. else:
  1559. # 降序排列:大 → 小,需要找到 prev_value > new_value > current_value 的位置
  1560. for j in range(len(sort_data)):
  1561. current_value = str(sort_data[j][0]) if sort_data[j] and len(sort_data[j]) > 0 else ""
  1562. prev_value = str(sort_data[j-1][0]) if j > 0 and sort_data[j-1] and len(sort_data[j-1]) > 0 else None
  1563. # 检查是否应该插入到当前位置
  1564. if prev_value is None:
  1565. # 这是第一个位置,检查是否应该插入到最前面
  1566. if new_sort_value > current_value:
  1567. insert_row = j + 2 # +2 因为表头偏移
  1568. print(f" 插入到最前面第{insert_row}行: 新值{new_sort_value} > 第一个值{current_value}")
  1569. break
  1570. else:
  1571. # 检查是否在两个相邻值之间
  1572. if new_sort_value <= prev_value and new_sort_value > current_value:
  1573. insert_row = j + 2 # +2 因为表头偏移
  1574. print(f" 插入到第{insert_row}行: {prev_value} >= {new_sort_value} > {current_value}")
  1575. break
  1576. elif new_sort_value == current_value:
  1577. # 值相等时插入到相等值之后
  1578. insert_row = j + 3 # +2(表头偏移) +1(插入到此行之后)
  1579. print(f" 插入到第{insert_row}行: 新值{new_sort_value} = 现有值{current_value},插入其后")
  1580. break
  1581. # 如果遍历完都没有找到位置,说明新值是最小的,插入到末尾
  1582. if insert_row == len(sort_data) + 2:
  1583. last_value = str(sort_data[-1][0]) if sort_data and sort_data[-1] and len(sort_data[-1]) > 0 else "无"
  1584. print(f" 插入到末尾第{insert_row}行: 新值{new_sort_value} < 最后一个值{last_value}")
  1585. print(f"[{i+1}/{len(valid_rows)}] 最终插入位置: 第 {insert_row} 行: {sort_field}={new_sort_value}")
  1586. # 插入数据到指定行(真正插入新行)
  1587. result = client.insert_row_with_data_at_position(access_token, sheet_token, sheet_id, insert_row, [new_row_values], True, grid_width, grid_height, border_width, border_color)
  1588. if result:
  1589. print(f"成功插入数据和图片到第 {insert_row} 行")
  1590. # 更新sort_data:在正确的位置添加新的排序值
  1591. sort_data_index = insert_row - 2 # 转换为sort_data的索引(-2因为表头偏移)
  1592. sort_data.insert(sort_data_index, [new_sort_value])
  1593. # 更新去重集合
  1594. existing_unique_values.add(new_unique_value)
  1595. else:
  1596. print(f"插入数据到第 {insert_row} 行失败")
  1597. if __name__ == "__main__":
  1598. # data = get_test_data()
  1599. # sheet_token = 'IoTOsjZ4khIqlOtTxnec8oTbn7c'
  1600. # sheetid = 'K9c4LG'
  1601. # write_data_to_sheet(data, sheetid=sheetid)
  1602. # is_image_cell_result = is_image_cell('["http://sns-webpic-qc.xhscdn.com/202501021415/1a6e88908930afce92b09206d5a482f8/1040g2sg31b74rf6k7g5g5oo7i8vkgev59lkjet0!nd_whlt34_webp_wm_1","http://sns-webpic-qc.xhscdn.com/202501021415/1a6e88908930afce92b09206d5a482f8/1040g2sg31b74rf6k7g5g5oo7i8vkgev59lkjet0!nd_whlt34_webp_wm_1"]')
  1603. # print(is_image_cell_result)
  1604. # 新增函数使用示例
  1605. """
  1606. 示例:使用 to_feishu_incremental 增量插入数据
  1607. # 测试数据
  1608. test_data = [
  1609. {
  1610. '内容ID': '1001',
  1611. '标题': '测试标题1',
  1612. '内容': '测试内容1',
  1613. '图片': '["http://example.com/image1.jpg", "http://example.com/image2.jpg"]'
  1614. },
  1615. {
  1616. '内容ID': '1003',
  1617. '标题': '测试标题2',
  1618. '内容': '测试内容2',
  1619. '图片': 'http://example.com/image3.jpg'
  1620. }
  1621. ]
  1622. # 调用增量插入函数
  1623. to_feishu_incremental(
  1624. res_list=test_data,
  1625. sort_field='内容ID', # 按此字段排序
  1626. sheet_id='your_sheet_id',
  1627. sheet_token='your_sheet_token',
  1628. unique_field='内容ID', # 去重字段,默认使用sort_field
  1629. duplicate_strategy='update', # 重复处理策略:'skip'跳过, 'delete'删除后插入, 'update'更新指定字段
  1630. update_fields=['标题', '内容', '图片'], # 当strategy='update'时,只更新这些字段
  1631. cleanup_duplicates=True, # 先清理现有表格中的重复数据
  1632. keep_first=True, # 清理时保留第一个重复项
  1633. sort_ascending=False, # 排序顺序:False为降序(大→小),True为升序(小→大)
  1634. grid_width=2, # 图片拼接列数
  1635. grid_height=2, # 图片拼接行数
  1636. )
  1637. # 排序方向示例:
  1638. # 示例1:按时间戳降序排序(最新的在前面)- 适合新闻、动态等时间敏感内容
  1639. to_feishu_incremental(
  1640. res_list=news_data,
  1641. sort_field='发布时间',
  1642. sort_ascending=False, # 降序,最新时间在前面
  1643. # ... 其他参数
  1644. )
  1645. # 示例2:按ID升序排序(从小到大)- 适合有明确编号顺序的内容
  1646. to_feishu_incremental(
  1647. res_list=product_data,
  1648. sort_field='产品ID',
  1649. sort_ascending=True, # 升序,小ID在前面
  1650. # ... 其他参数
  1651. )
  1652. # 示例3:按优先级降序排序(高优先级在前面)- 适合任务、问题等需要优先级管理的内容
  1653. to_feishu_incremental(
  1654. res_list=task_data,
  1655. sort_field='优先级',
  1656. sort_ascending=False, # 降序,高优先级在前面
  1657. # ... 其他参数
  1658. )
  1659. 功能说明:
  1660. 1. **智能表头处理**:
  1661. - 如果表格为空,自动从数据中提取字段名创建表头
  1662. - 如果表格已有数据,读取现有表头结构
  1663. 2. **空白行清理**:
  1664. - 自动检测并删除排序字段和去重字段都为空的空白行
  1665. - 确保数据的连续性和逻辑一致性
  1666. 3. **重复数据清理**:
  1667. - cleanup_duplicates=True: 先清理现有表格中的重复数据
  1668. - keep_first: 保留第一个或最后一个重复项
  1669. 4. **智能去重检查**:
  1670. - 基于 unique_field 字段检查数据是否已存在
  1671. - 预处理阶段过滤重复数据,避免插入过程中的状态变化问题
  1672. 5. **排序插入**:根据指定的 sort_field 字段和 sort_ascending 参数查找插入位置
  1673. - sort_ascending=False(默认):降序排序,较大的值插入到较前面的位置
  1674. - sort_ascending=True:升序排序,较小的值插入到较前面的位置
  1675. 6. **逐行数据插入**:按排序顺序逐行插入数据,保持表格整体有序
  1676. 7. **完整图片支持**:自动处理图片写入,支持单张图片和图片列表
  1677. 8. **图片拼接功能**:支持多图拼接,可设置拼接的行列数和边框样式
  1678. 适用场景:
  1679. - ✅ 空表格:自动创建表头并插入数据
  1680. - ✅ 已有重复数据的表格:先清理重复,再智能插入
  1681. - ✅ 增量数据更新:逐条插入,保持排序,自动去重
  1682. - ✅ 重复运行安全:不会插入重复数据
  1683. - ✅ 数据清理:一键清理现有重复数据
  1684. - ✅ 灵活排序:支持升序和降序两种排序方式
  1685. """