Commit ·
9167aa8
0
Parent(s):
Initial commit for Hugging Face Space
Browse files- .gitignore +5 -0
- .streamlit/config.toml +2 -0
- .trae/documents/Create Bitbcpy Streamlit Tool.md +40 -0
- bitbcpy.py +328 -0
- requirements.txt +5 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
.DS_Store
|
| 5 |
+
.streamlit/secrets.toml
|
.streamlit/config.toml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[browser]
|
| 2 |
+
gatherUsageStats = false
|
.trae/documents/Create Bitbcpy Streamlit Tool.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Bitbcpy: Multidimensional Table Sync Tool (Updated)
|
| 2 |
+
|
| 3 |
+
I will build a Streamlit application called `bitbcpy` that syncs data between two Feishu/Lark Bitables, with added validation for Primary Keys.
|
| 4 |
+
|
| 5 |
+
## Project Structure
|
| 6 |
+
- `requirements.txt`: Dependencies (`streamlit`, `lark-oapi`).
|
| 7 |
+
- `bitbcpy.py`: Main application script.
|
| 8 |
+
|
| 9 |
+
## UI Design
|
| 10 |
+
- **Sidebar**: Inputs for App ID and App Secret.
|
| 11 |
+
- **Main Interface**:
|
| 12 |
+
- Source Table URL & Target Table URL.
|
| 13 |
+
- "Start Merge" Button.
|
| 14 |
+
- Progress Bar & Status Messages.
|
| 15 |
+
|
| 16 |
+
## Core Logic & API Usage
|
| 17 |
+
Based on the provided documentation:
|
| 18 |
+
1. **Validation Phase (New)**:
|
| 19 |
+
- Call `List Fields` API for both Source and Target tables.
|
| 20 |
+
- Identify the **Primary Key** field in both tables (where `is_primary=True`).
|
| 21 |
+
- **Constraint**: Verify that Source PK and Target PK have the **same Name and same Type**.
|
| 22 |
+
- If validation fails, halt and display a clear error message.
|
| 23 |
+
|
| 24 |
+
2. **Data Fetching**:
|
| 25 |
+
- Use `Batch Get` (List Records) to retrieve all records from the Source table.
|
| 26 |
+
- Pagination will be handled to ensure large datasets are fully captured.
|
| 27 |
+
|
| 28 |
+
3. **Data Transformation**:
|
| 29 |
+
- Map Source fields to Target fields by **Field Name**.
|
| 30 |
+
- Filter out Source fields that do not exist in the Target schema.
|
| 31 |
+
- **Special Column**: Populate "控制台链接" with the source record's URL.
|
| 32 |
+
|
| 33 |
+
4. **Data Writing**:
|
| 34 |
+
- Use `Batch Create` API to insert records into the Target table.
|
| 35 |
+
- Operations will be batched (e.g., 50-100 records per request) for performance.
|
| 36 |
+
|
| 37 |
+
## References
|
| 38 |
+
- `bitable-v1/app-table-record/bitable-record-data-structure-overview`
|
| 39 |
+
- `bitable-v1/app-table-record/create`
|
| 40 |
+
- `bitable-v1/app-table-record/batch_get`
|
bitbcpy.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import re
|
| 3 |
+
import lark_oapi as lark
|
| 4 |
+
from lark_oapi.api.bitable.v1 import *
|
| 5 |
+
import time
|
| 6 |
+
import openpyxl
|
| 7 |
+
import os
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
import logging
|
| 10 |
+
from tenacity import retry, stop_after_attempt, wait_exponential
|
| 11 |
+
|
| 12 |
+
# Configure logging
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
# Load environment variables
|
| 17 |
+
load_dotenv()
|
| 18 |
+
|
| 19 |
+
def parse_bitable_url(url):
|
| 20 |
+
"""
|
| 21 |
+
Extracts app_token and table_id from a Bitable URL.
|
| 22 |
+
Expected format: .../base/<app_token>?table=<table_id>...
|
| 23 |
+
"""
|
| 24 |
+
try:
|
| 25 |
+
# Extract app_token
|
| 26 |
+
app_token_match = re.search(r'/base/([^/?]+)', url)
|
| 27 |
+
if not app_token_match:
|
| 28 |
+
return None, None
|
| 29 |
+
app_token = app_token_match.group(1)
|
| 30 |
+
|
| 31 |
+
# Extract table_id
|
| 32 |
+
table_id_match = re.search(r'table=([^&]+)', url)
|
| 33 |
+
if not table_id_match:
|
| 34 |
+
return None, None
|
| 35 |
+
table_id = table_id_match.group(1)
|
| 36 |
+
|
| 37 |
+
return app_token, table_id
|
| 38 |
+
except Exception:
|
| 39 |
+
return None, None
|
| 40 |
+
|
| 41 |
+
def get_bitable_client(app_id, app_secret):
|
| 42 |
+
return lark.Client.builder().app_id(app_id).app_secret(app_secret).build()
|
| 43 |
+
|
| 44 |
+
def get_table_fields(client, app_token, table_id):
|
| 45 |
+
logger.info(f"Fetching fields for app_token={app_token}, table_id={table_id}")
|
| 46 |
+
fields = []
|
| 47 |
+
page_token = None
|
| 48 |
+
has_more = True
|
| 49 |
+
|
| 50 |
+
while has_more:
|
| 51 |
+
req = ListAppTableFieldRequest.builder() \
|
| 52 |
+
.app_token(app_token) \
|
| 53 |
+
.table_id(table_id) \
|
| 54 |
+
.page_size(100)
|
| 55 |
+
|
| 56 |
+
if page_token:
|
| 57 |
+
req.page_token(page_token)
|
| 58 |
+
|
| 59 |
+
req = req.build()
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
resp = client.bitable.v1.app_table_field.list(req)
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logger.error(f"API call failed: {e}", exc_info=True)
|
| 65 |
+
raise
|
| 66 |
+
|
| 67 |
+
if not resp.success():
|
| 68 |
+
logger.error(f"Failed to list fields: code={resp.code}, msg={resp.msg}, log_id={resp.get_log_id()}")
|
| 69 |
+
raise Exception(f"Failed to list fields: {resp.msg}, log_id: {resp.get_log_id()}")
|
| 70 |
+
|
| 71 |
+
if resp.data and resp.data.items:
|
| 72 |
+
fields.extend(resp.data.items)
|
| 73 |
+
logger.info(f"Fetched {len(resp.data.items)} fields. Current total: {len(fields)}")
|
| 74 |
+
logger.info(f"Page token: {page_token} -> {resp.data.page_token}, Has more: {resp.data.has_more}")
|
| 75 |
+
|
| 76 |
+
# Determine if we should continue based on result count
|
| 77 |
+
# Some APIs return has_more=True even if they return fewer items than page_size on the last page.
|
| 78 |
+
# But generally, if len(items) < page_size, it's the last page.
|
| 79 |
+
# Or if len(items) == 0, we are done.
|
| 80 |
+
|
| 81 |
+
items_count = len(resp.data.items) if (resp.data and resp.data.items) else 0
|
| 82 |
+
|
| 83 |
+
if items_count < 100:
|
| 84 |
+
has_more = False
|
| 85 |
+
else:
|
| 86 |
+
has_more = resp.data.has_more
|
| 87 |
+
|
| 88 |
+
# Still keep the infinite loop safeguard just in case
|
| 89 |
+
new_page_token = resp.data.page_token
|
| 90 |
+
|
| 91 |
+
if has_more and new_page_token == page_token:
|
| 92 |
+
logger.warning("Infinite loop detected: page_token did not update. Breaking.")
|
| 93 |
+
has_more = False
|
| 94 |
+
|
| 95 |
+
page_token = new_page_token
|
| 96 |
+
|
| 97 |
+
logger.info(f"Total fields fetched: {len(fields)}")
|
| 98 |
+
return fields
|
| 99 |
+
|
| 100 |
+
def validate_primary_keys(excel_columns, target_fields):
|
| 101 |
+
# For Excel, we assume the first column is the primary key (or at least the one to check against)
|
| 102 |
+
# But usually Excel doesn't have strict schema.
|
| 103 |
+
# However, the user asked to check "Primary Key Name Type".
|
| 104 |
+
# We can check if the Target PK name exists in Excel columns.
|
| 105 |
+
|
| 106 |
+
target_pk = next((f for f in target_fields if f.is_primary), None)
|
| 107 |
+
|
| 108 |
+
if not target_pk:
|
| 109 |
+
return False, "Target table has no primary key."
|
| 110 |
+
|
| 111 |
+
if target_pk.field_name not in excel_columns:
|
| 112 |
+
return False, f"Target Primary Key '{target_pk.field_name}' not found in Excel columns."
|
| 113 |
+
|
| 114 |
+
# We can't strictly validate TYPE from Excel as Excel types are loose,
|
| 115 |
+
# but we validated the existence of the PK column.
|
| 116 |
+
return True, f"Primary key '{target_pk.field_name}' found in Excel."
|
| 117 |
+
|
| 118 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 119 |
+
def _send_batch(client, app_token, table_id, records):
|
| 120 |
+
req = BatchCreateAppTableRecordRequest.builder() \
|
| 121 |
+
.app_token(app_token) \
|
| 122 |
+
.table_id(table_id) \
|
| 123 |
+
.request_body(BatchCreateAppTableRecordRequestBody.builder().records(records).build()) \
|
| 124 |
+
.build()
|
| 125 |
+
|
| 126 |
+
resp = client.bitable.v1.app_table_record.batch_create(req)
|
| 127 |
+
if not resp.success():
|
| 128 |
+
logger.error(f"Batch create failed: code={resp.code}, msg={resp.msg}, log_id={resp.get_log_id()}")
|
| 129 |
+
if resp.error:
|
| 130 |
+
logger.error(f"Error details: {resp.error}")
|
| 131 |
+
raise Exception(f"Batch create failed: {resp.msg}, log_id: {resp.get_log_id()}")
|
| 132 |
+
|
| 133 |
+
def sync_data(client, excel_rows, excel_columns, special_col_name, manual_source_value, excel_file_name, target_app_token, target_table_id, target_fields):
|
| 134 |
+
target_field_names = {f.field_name: f for f in target_fields}
|
| 135 |
+
|
| 136 |
+
batch_records = []
|
| 137 |
+
total_records = len(excel_rows)
|
| 138 |
+
|
| 139 |
+
if total_records == 0:
|
| 140 |
+
st.warning("No records to sync.")
|
| 141 |
+
return
|
| 142 |
+
|
| 143 |
+
progress_bar = st.progress(0)
|
| 144 |
+
status_text = st.empty()
|
| 145 |
+
processed_count = 0
|
| 146 |
+
|
| 147 |
+
for row in excel_rows:
|
| 148 |
+
new_fields = {}
|
| 149 |
+
# row is a tuple/list matching excel_columns order
|
| 150 |
+
|
| 151 |
+
row_dict = dict(zip(excel_columns, row))
|
| 152 |
+
|
| 153 |
+
# 1. Copy common fields
|
| 154 |
+
for col_name, val in row_dict.items():
|
| 155 |
+
if col_name in target_field_names and val is not None:
|
| 156 |
+
# Basic type conversion for API
|
| 157 |
+
# Excel reads everything as is (int, float, datetime, string)
|
| 158 |
+
# API expects specific formats sometimes.
|
| 159 |
+
# For simplicity, we send as is, assuming Lark SDK or API handles basic types.
|
| 160 |
+
# DateTime might need conversion to timestamp if API requires it.
|
| 161 |
+
# Lark API expects Unix timestamp (ms) for Date fields usually.
|
| 162 |
+
target_type = target_field_names[col_name].type
|
| 163 |
+
|
| 164 |
+
if target_type == 5: # Date
|
| 165 |
+
if hasattr(val, 'timestamp'): # datetime object
|
| 166 |
+
new_fields[col_name] = int(val.timestamp() * 1000)
|
| 167 |
+
else:
|
| 168 |
+
new_fields[col_name] = val
|
| 169 |
+
elif target_type == 4: # MultiSelect
|
| 170 |
+
# Excel might have comma separated string?
|
| 171 |
+
if isinstance(val, str):
|
| 172 |
+
new_fields[col_name] = [v.strip() for v in val.split(',')]
|
| 173 |
+
else:
|
| 174 |
+
new_fields[col_name] = val
|
| 175 |
+
elif target_type == 11: # User
|
| 176 |
+
# User field is complex (list of objects). Excel might just have names.
|
| 177 |
+
# We might skip or try to pass simple text?
|
| 178 |
+
# Writing text to User field usually fails or requires specific format.
|
| 179 |
+
# Let's skip complex fields for now or assume user knows what they are doing.
|
| 180 |
+
pass
|
| 181 |
+
else:
|
| 182 |
+
new_fields[col_name] = val
|
| 183 |
+
|
| 184 |
+
# 2. Handle Special "Source Record" Column
|
| 185 |
+
if special_col_name and special_col_name in target_field_names:
|
| 186 |
+
target_col_def = target_field_names[special_col_name]
|
| 187 |
+
|
| 188 |
+
# Use manual value provided by user if available, otherwise fallback to filename
|
| 189 |
+
final_val = manual_source_value if manual_source_value else f"Imported from {excel_file_name}"
|
| 190 |
+
|
| 191 |
+
if target_col_def.type == 15: # Hyperlink
|
| 192 |
+
# If final_val is a string that looks like a URL, use it
|
| 193 |
+
# If it's just text, treat as text
|
| 194 |
+
link_url = str(final_val) if final_val else ""
|
| 195 |
+
if not link_url.startswith("http"):
|
| 196 |
+
link_url = "" # Can't link if no URL
|
| 197 |
+
|
| 198 |
+
new_fields[special_col_name] = {
|
| 199 |
+
"link": link_url,
|
| 200 |
+
"text": str(final_val)
|
| 201 |
+
}
|
| 202 |
+
else:
|
| 203 |
+
new_fields[special_col_name] = final_val
|
| 204 |
+
|
| 205 |
+
batch_records.append(AppTableRecord.builder().fields(new_fields).build())
|
| 206 |
+
|
| 207 |
+
if len(batch_records) >= 100:
|
| 208 |
+
_send_batch(client, target_app_token, target_table_id, batch_records)
|
| 209 |
+
processed_count += len(batch_records)
|
| 210 |
+
progress_bar.progress(processed_count / total_records)
|
| 211 |
+
status_text.text(f"Synced {processed_count}/{total_records} records")
|
| 212 |
+
batch_records = []
|
| 213 |
+
|
| 214 |
+
if batch_records:
|
| 215 |
+
_send_batch(client, target_app_token, target_table_id, batch_records)
|
| 216 |
+
processed_count += len(batch_records)
|
| 217 |
+
progress_bar.progress(1.0)
|
| 218 |
+
status_text.text(f"Synced {processed_count}/{total_records} records")
|
| 219 |
+
|
| 220 |
+
def main():
|
| 221 |
+
st.set_page_config(page_title="Bitbcpy - 多维表格合并工具", layout="wide")
|
| 222 |
+
st.title("Bitbcpy - 多维表格合并脚本")
|
| 223 |
+
st.markdown("将本地 Excel 的行抄到目标表,同名列合并,忽略目标表不存在的列。")
|
| 224 |
+
|
| 225 |
+
if 'target_fields' not in st.session_state:
|
| 226 |
+
st.session_state.target_fields = []
|
| 227 |
+
if 'target_fields_loaded' not in st.session_state:
|
| 228 |
+
st.session_state.target_fields_loaded = False
|
| 229 |
+
|
| 230 |
+
with st.sidebar:
|
| 231 |
+
st.header("配置")
|
| 232 |
+
|
| 233 |
+
default_app_id = os.getenv("LARK_OAPI_APPID", "")
|
| 234 |
+
default_app_secret = os.getenv("LARK_OAPI_SECRET", "")
|
| 235 |
+
|
| 236 |
+
app_id = st.text_input("App ID", value=default_app_id)
|
| 237 |
+
app_secret = st.text_input("App Secret", type="password", value=default_app_secret)
|
| 238 |
+
|
| 239 |
+
target_url = st.text_input("目标文档链接")
|
| 240 |
+
|
| 241 |
+
if st.button("读取目标表字段"):
|
| 242 |
+
if not app_id or not app_secret:
|
| 243 |
+
st.error("请填写 App ID 和 App Secret")
|
| 244 |
+
elif not target_url:
|
| 245 |
+
st.error("请填写目标文档链接")
|
| 246 |
+
else:
|
| 247 |
+
t_token, t_table = parse_bitable_url(target_url)
|
| 248 |
+
if not (t_token and t_table):
|
| 249 |
+
st.error("目标链接解析失败")
|
| 250 |
+
else:
|
| 251 |
+
client = get_bitable_client(app_id, app_secret)
|
| 252 |
+
try:
|
| 253 |
+
with st.spinner("Fetching schema..."):
|
| 254 |
+
fields = get_table_fields(client, t_token, t_table)
|
| 255 |
+
st.session_state.target_fields = fields
|
| 256 |
+
st.session_state.target_fields_loaded = True
|
| 257 |
+
st.success("字段加载成功")
|
| 258 |
+
except Exception as e:
|
| 259 |
+
st.error(f"Error: {str(e)}")
|
| 260 |
+
|
| 261 |
+
source_col = None
|
| 262 |
+
manual_source_val = None
|
| 263 |
+
|
| 264 |
+
if st.session_state.target_fields_loaded:
|
| 265 |
+
field_names = [f.field_name for f in st.session_state.target_fields]
|
| 266 |
+
source_col = st.selectbox("哪一列记录来源", options=field_names)
|
| 267 |
+
manual_source_val = st.text_input("该列统一填写的来源信息", help="例如:2023年Q1销售数据")
|
| 268 |
+
|
| 269 |
+
uploaded_file = st.file_uploader("上传来源 Excel (xlsx)", type=['xlsx'])
|
| 270 |
+
|
| 271 |
+
if st.button("开始合并"):
|
| 272 |
+
if not app_id or not app_secret:
|
| 273 |
+
st.error("请在左侧侧边栏填写 App ID 和 App Secret")
|
| 274 |
+
return
|
| 275 |
+
|
| 276 |
+
if not uploaded_file:
|
| 277 |
+
st.error("请上传来源 Excel 文件")
|
| 278 |
+
return
|
| 279 |
+
|
| 280 |
+
t_token, t_table = parse_bitable_url(target_url)
|
| 281 |
+
|
| 282 |
+
if not (t_token and t_table):
|
| 283 |
+
st.error("目标链接解析失败,请检查链接格式")
|
| 284 |
+
return
|
| 285 |
+
|
| 286 |
+
client = get_bitable_client(app_id, app_secret)
|
| 287 |
+
|
| 288 |
+
try:
|
| 289 |
+
# Read Excel
|
| 290 |
+
wb = openpyxl.load_workbook(uploaded_file, data_only=True)
|
| 291 |
+
sheet = wb.active
|
| 292 |
+
|
| 293 |
+
# Assuming first row is header
|
| 294 |
+
rows = list(sheet.iter_rows(values_only=True))
|
| 295 |
+
if not rows:
|
| 296 |
+
st.error("Excel 文件为空")
|
| 297 |
+
return
|
| 298 |
+
|
| 299 |
+
header = rows[0]
|
| 300 |
+
data_rows = rows[1:]
|
| 301 |
+
|
| 302 |
+
# Filter None headers
|
| 303 |
+
excel_columns = [str(h) for h in header if h is not None]
|
| 304 |
+
|
| 305 |
+
# Use cached fields if available, else fetch
|
| 306 |
+
t_fields = st.session_state.target_fields
|
| 307 |
+
if not t_fields:
|
| 308 |
+
with st.spinner("Fetching target table schema..."):
|
| 309 |
+
t_fields = get_table_fields(client, t_token, t_table)
|
| 310 |
+
|
| 311 |
+
valid, msg = validate_primary_keys(excel_columns, t_fields)
|
| 312 |
+
if not valid:
|
| 313 |
+
st.error(f"主键校验失败: {msg}")
|
| 314 |
+
return
|
| 315 |
+
else:
|
| 316 |
+
st.success("主键校验通过")
|
| 317 |
+
|
| 318 |
+
st.info(f"Found {len(data_rows)} records in Excel.")
|
| 319 |
+
|
| 320 |
+
sync_data(client, data_rows, excel_columns, source_col, manual_source_val, uploaded_file.name, t_token, t_table, t_fields)
|
| 321 |
+
st.success("合并完成!")
|
| 322 |
+
|
| 323 |
+
except Exception as e:
|
| 324 |
+
logger.error(f"Error in main loop: {e}", exc_info=True)
|
| 325 |
+
st.error(f"Error: {str(e)}")
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
lark-oapi
|
| 3 |
+
openpyxl
|
| 4 |
+
python-dotenv
|
| 5 |
+
tenacity
|