Google表格 - 从硬盘获取文件名并插入表格 - (模拟Excel Application.GetOpenFilename)

时间:2015-03-04 19:06:22

标签: javascript file google-apps-script google-sheets filepicker

在Excel中,我可以使用application.getopenfilename运行VBA脚本,并且可以将所选项目的文件路径放入该单元格中。我正在尝试转换我的VBA

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

  If Not Application.Intersect(Target, Range("AG4:AG910")) Is Nothing Then
  Dim FileNames As Variant
  Dim Msg As String
  Dim i As Integer
  FileNames = Application.GetOpenFilename(MultiSelect:=True)
  If IsArray(FileNames) Then
      For i = LBound(FileNames) To UBound(FileNames)
          Msg = Msg & FileNames(i) & vbNewLine
      Next i
      Target = Msg
          Else
      MsgBox "No files were selected."
End If

End If

基本上我希望能够选择图像,然后获取文件名。我只需要文件名,因为客户向我发送了产品图片,然后我必须在上传之前对其进行优化。

1 个答案:

答案 0 :(得分:0)

此解释显示:

  • 自动创建自定义菜单项
  • 打开对话框的代码
  • HTML和<script>标记在对话框的HTML中
  • 将结果放入电子表格的代码

Code.gs - onOpen() - 创建自定义菜单

function onOpen() {

  SpreadsheetApp.getUi()
      .createMenu('Custom Menu')
      .addItem('Show Upload Dialog', 'showUploadBox')
      .addToUi();
};

gs代码 - 打开对话框

function showUploadBox() {

  var htmlOutput = HtmlService.createHtmlOutputFromFile('Dialog')
     .setWidth(500)
     .setHeight(500);

  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Title of Dialog');
};

Dialog Upload.html

使用此HTML

创建一个新文件
<div id="formDiv">

<form id="myForm">

    <input id="fileName" name="picToLoad" type="file" />
    <br>
    <br/>
    <input type="button" value="Submit" onclick="fncGetFileName()" />
  <br>
  <br>
  <br>
    <input id="idBtnClose" type="button" value="Close" style="display: none" onclick="google.script.host.close()" />
</form>
</div>

<br>
<br>

<div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Working. Please wait...
</div>


<script>

function fncGetFileName(frmData) {
  console.log('fncGetFileName ran!');

  var theFileName = document.getElementById('fileName').value;
  theFileName = theFileName.slice(12);

  console.log('theFileName: ' + theFileName);

  document.getElementById('status').style.display = 'inline'; //Display msg

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(theFileName)
};
  // Javascript function called by "submit" button handler,
  // to show results.

  function updateOutput() {

    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File Name was Written!";

    document.getElementById('idBtnClose').style.display = 'inline'; //Display msg
  }

</script>

gs将文件名保存到工作表的代码

function processForm(argFileName) {
  Logger.log('argFileName: ' + argFileName);

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var theSheet = ss.getActiveSheet();

  var theRange = theSheet.getRange("B4");
  theRange.setValue(argFileName);
};