问题
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