Put brackets around filename for Excel formula

谁都会走 提交于 2019-12-11 11:58:20

问题


My project is based on Apache POI.I'm trying to use a formula on a cell. My formula is as follows.

sheet7.createRow(0).createCell(0).setCellFormula("+'C:\\Users\\Desktop\\[Test.xlsx]Average_Graph'!A2");

Im using a JFileChooser, which allows users to select the file. Therefore the filepath will be changed every time the program is used.

From the JFileChooser, I'm getting a filepath as follows.

 String filepath= "C:\\Users\\Desktop\\Sheet.xlsx"`

In order to work the formula correctly, the filepath should be in following format.

"C:\\Users\\Desktop[Sheet.xlsx]"

How Can I Change the string which I'm getting from the JFileCHooser to run the formula correctly?


回答1:


If you have a JFileChooser, you have a File object, not just a String

And you should use the File or Paths API anyway to be OS independent

File f = jFileChooser.getSelectedFile();
String path = f.getParent();
String name = f.getName();

String newFormat = String.format("%s[%s]", path, name);



回答2:


As I understand it you get the path as a String from a file chooser. So in your example you can do:

   String filepath= "C:\\Users\\Desktop\\Sheet.xlsx"
   Path path = Paths.get(filepath);
   String result=path.getParent()+"["+path.getFileName()+"]";

And result will be your new string containing the file surrounded by braces

Or another solution would be using a File

  File f=new File(filepath);
  String result=f.getParent()+"["+f.getName()+"]";



回答3:


Just split parent directonary name and file name and putting the chars "[" and "]" around the file name:

    File select = fileC.getSelectedFile();
    String filepath = select.getParentFile().getAbsolutePath()+"["+select.getName()+"]";

*EDIT i understood the question wrong so i thought about the false problem;



来源:https://stackoverflow.com/questions/51999652/put-brackets-around-filename-for-excel-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!