如何将Salesbinder API发票数据导入指定格式的Google Sheet
解决Salesbinder发票API数据导入Google Sheets的格式整理问题
以下是适配需求的Google Apps Script代码,可直接修改配置后使用:
function importSalesbinderInvoice() { // 替换为你的Salesbinder API密钥 const API_KEY = 'YOUR_SALESBINDER_API_KEY'; const INVOICE_ENDPOINT = 'https://api.salesbinder.com/v1/invoices'; // 获取Sheet2的A1单元格中的发票编号 const ss = SpreadsheetApp.getActiveSpreadsheet(); const invoiceSheet = ss.getSheetByName('Sheet2'); const invoiceNumber = invoiceSheet.getRange('A1').getValue().toString().trim(); if (!invoiceNumber) { SpreadsheetApp.getUi().alert('Sheet2的A1单元格未填写发票编号'); return; } // 调用API获取发票数据 let response; try { const url = `${INVOICE_ENDPOINT}?number=${encodeURIComponent(invoiceNumber)}`; const options = { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' } }; response = UrlFetchApp.fetch(url, options); } catch (e) { SpreadsheetApp.getUi().alert(`API调用失败:${e.message}`); return; } // 解析API返回的JSON数据 const invoiceData = JSON.parse(response.getContentText()); if (!invoiceData.invoices || invoiceData.invoices.length === 0) { SpreadsheetApp.getUi().alert('未找到对应编号的发票'); return; } const invoice = invoiceData.invoices[0]; // 整理成目标表格格式:发票头信息+商品项,每行对应一个商品 const outputRows = []; // 表头(可根据目标表格列名调整) outputRows.push([ '发票编号', '客户名称', '发票日期', '到期日期', '商品名称', '数量', '单价', '商品金额' ]); // 遍历商品项生成数据行 invoice.items.forEach(item => { outputRows.push([ invoice.number, invoice.customer_name, invoice.date, invoice.due_date, item.name, item.quantity, item.unit_price, item.amount ]); }); // 写入目标Sheet(若Sheet1不存在则自动创建) const targetSheet = ss.getSheetByName('Sheet1') || ss.insertSheet('Sheet1'); targetSheet.clearContents(); targetSheet.getRange(1, 1, outputRows.length, outputRows[0].length).setValues(outputRows); // 自动调整列宽 targetSheet.autoResizeColumns(1, outputRows[0].length); SpreadsheetApp.getUi().alert('发票数据已成功导入'); }
关键调整说明
- API配置:替换
YOUR_SALESBINDER_API_KEY为你的实际API密钥,确保密钥拥有发票读取权限。 - 字段适配:如果目标表格的列名或字段与示例不同,只需修改:
- 表头数组
outputRows[0]的字段名称,与目标表格列名匹配 - 商品项循环中
outputRows.push()的属性,从invoice或item对象中提取对应字段(可通过Logger.log(JSON.stringify(invoice))查看所有可用字段)
- 表头数组
- 异常处理:代码包含空值、API调用失败、无发票数据的场景提示,避免静默报错。
内容的提问来源于stack exchange,提问作者Yvan L
相关产品推荐
相关产品推荐

