You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Apps Script实现Gsheets跨文件复制并保留源格式?

Fix: Preserve Text-Formatted Numbers When Copying Between Google Sheets via Apps Script

Hey there, let's sort out this formatting issue you're facing!

Why Your Current Code Loses Formatting

The getValues() and setValues() methods you're using only handle the raw values of cells—they don't carry over any formatting information. That's why your text-formatted numbers are being automatically converted to number format in the destination sheet; the script isn't preserving the original cell's format.

The Solution: Use copyTo() Instead

To keep both values and their original formatting (including text-formatted numbers), switch to the Range.copyTo() method. This method lets you explicitly copy values along with their formats, which is exactly what you need.

Here's your revised code:

function Run_function1() {
  var ss = SpreadsheetApp.openById("Destination ID");
  const sk = ss.getSheetByName('Settings WS');
  var cc = sk.getRange("cell with origin file ID").getValue();
  const sh = ss.getSheetByName('Destination WS');
  
  // Clear existing content in the destination sheet
  sh.getRange(2, 1, sh.getLastRow(), 30).clearContent();
  
  var dbss = SpreadsheetApp.openById(cc);
  const dbsh = dbss.getSheetByName('Origin WS');
  const sourceRange = dbsh.getRange(2, 1, dbsh.getLastRow() - 1, 25);
  
  // Copy values AND formats to the destination range
  sourceRange.copyTo(
    sh.getRange(2, 1, sourceRange.getNumRows(), sourceRange.getNumColumns()),
    SpreadsheetApp.CopyPasteType.PASTE_VALUES_AND_FORMATS,
    false
  );
}

Key Details About the Revision

  • SpreadsheetApp.CopyPasteType.PASTE_VALUES_AND_FORMATS: This parameter tells the script to copy both the cell values and their formatting. This ensures your text-formatted numbers stay as text in the destination sheet.
  • We first define the full source range, then directly copy it to the destination range—no more converting values to arrays and back, which was causing the format loss.
  • If you ever need to copy additional properties (like formulas, data validation rules, or conditional formatting), you can replace the paste type with SpreadsheetApp.CopyPasteType.PASTE_NORMAL instead.

Quick Extra Tip

If you want to completely reset the destination area before copying, replace clearContent() with clear()—this will wipe both existing content and formatting, so the destination sheet fully inherits the source's style.

内容的提问来源于stack exchange,提问作者user13332855

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:07:45