使用纯文本单元格创建Google表格以防止字符串的自动格式化

时间:2016-04-13 17:16:27

标签: google-apps-script google-sheets

我与一群经常需要编辑包含看起来像日期和数字的字符串的CSV文件的用户合作。这些字符串需要保存为字符串。

例如

2016-04

转换为日期字段

4/1/2016

编辑新电子表格时,我们必须将每个单元格的格式设置为TEXT /纯文本以防止此转换。导入现有CSV文件时,我们需要阻止进行此转换。

不幸的是,Excel和Google表格会在导入或文件打开时自动转换字符串。

在Google表格中阻止此转化的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

以下是我目前使用Google Apps脚本创建将CSV内容转换为新Google表单的网络服务的解决方案。

<强> Code.gs

//Display the interactive landing page for this servcie
function doGet() {
  var html = HtmlService.createHtmlOutputFromFile('Index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  return html;
}

//Create a global object to store the response from a POST request
var RESP;

//Handle a POST request directly to this service.  
//The parameter "data" should contain CSV content
//A response page will be generated with a link to the Google Sheet that is generated
function doPost(req) {
  RESP = createPlainTextSpreadsheet(req.parameter.data);
  var temp = HtmlService.createTemplateFromFile('Response');
  return temp.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

//Handle CSV content sent from the interactive landing page for this script
//Return a string representation of a JSON object with the name and URL of the generated Google Sheet
function doTextPost(req) {
  var resp = createPlainTextSpreadsheet(req.data);
  return JSON.stringify(resp);
}

//Handle file upload content sent from the interactive landing page for this script
//Return a string representation of a JSON object with the name and URL of the generated Google Sheet
function processFile(form) {
  var blob = form.file;
  var resp = createPlainTextSpreadsheet(blob.getDataAsString());
  return JSON.stringify(resp);
}

//Generate a new Google Sheet containing the CSV data that is provided
//The new Google Sheet will be named "import.YYYY-MM-DD_HH:MM.csv in Google Drive
//All data cells will be set as "Plain Text" to prevent auto-conversion of strings that look like dates and numbers
//Text wrap will be enabled for all data cells
//The header row will be highlighted and the columns will be auto-sized
//Return a JSON object containing the name and URL of the new Google Sheet
function createPlainTextSpreadsheet(data) {
  var arr = Utilities.parseCsv(data);
  if (arr.length == 0) return "No data";

  var formattedDate = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd_HH:mm");
  var spreadsheet = SpreadsheetApp.create("import."+formattedDate+".csv");
  var sheet = spreadsheet.getActiveSheet();
  var range = sheet.getRange(1, 1, arr.length, arr[0].length);
  var rangeR1 = sheet.getRange(1, 1, 1, arr[0].length);
  range.setValue("");
  range.setNumberFormat("@STRING@");
  range.setValues(arr);
  range.setWrap(true);
  rangeR1.setBackground("yellow");
  rangeR1.setFontWeight("bold");
  for(var i=1; i<=arr[0].length; i++) {
    sheet.autoResizeColumn(i);
    if (sheet.getColumnWidth(i) > 300) {
      sheet.setColumnWidth(i, 300);
    }
  }

  return {name: spreadsheet.getName(), url: spreadsheet.getUrl()};
}

<强>的index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
      //Pass the uploaded file object (formObject.file) to the web service, extract CSV content from the uploaded file
      function handleFormSubmit(formObject) {
        jQuery("input:button").attr("disabled",true);
        google.script.run.withSuccessHandler(updateOutput).withFailureHandler(fail).processFile(formObject);
      }
      //Pass CSV content as a string (formObject.data)
      function handleFormPost(formObject) {
        jQuery("input:button").attr("disabled",true);
        google.script.run.withSuccessHandler(updateOutput).withFailureHandler(fail).doTextPost(formObject);
      }
      //Display the name and URL of the Google Sheet that was created
      function updateOutput(data) {
        var resp  = jQuery.parseJSON(data);
        document.getElementById("output").innerHTML="<a href='"+resp.url+"'>"+resp.name+"</a> created on Google Drive";
      }
      //Display and error dialog
      function fail(data) {
        alert("FAIL: "+data);
      }
    </script>
  </head>
  <body>
    <h1>Create a Plain Text Google Spreadsheet That Prevents Auto-Format of Data Cells</h1>
    <div>In addition to the forms provided below, you can POST data to this webservice directly.</div>
    <h2>Upload a CSV File</h2>
    <form id="myForm">
      <div>
        <label for="file">CSV File to Upload</label>
        <input name="file" type="file"/>
      </div>
      <div>
        <input type="button" value="Upload CSV" name="button" onclick="handleFormSubmit(document.getElementById('myForm'))"/>
      </div>
    </form>
    <hr/>
    <h2>Upload the Text from a CSV file</h2>
    <form id="myPostForm" method="POST">
      <div>
        <label for="data">CSV File to Upload</label>
        <br/>
        <textarea name="data" rows="10" cols="100"></textarea>
      </div>
      <div>
        <input type="button" value="Upload Data" name="button" onclick="handleFormPost(document.getElementById('myPostForm'))"/>
      </div>
    </form>
    <hr/>
    <h2>Link to new Spreadsheet</h2>
    <div id="output">Upload CSV text in order to generate a new Google Sheet</div>
  </body>
</html>

<强> Response.html

<!DOCTYPE html>
<html>
  <body>
    <a href="<?= RESP.url ?>">Google Sheet <?= RESP.name ?> Created</a>
  </body>
</html>