0

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? I need TWO backslashes instead of one. Please help.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
LSH94
  • 109
  • 1
  • 9
  • 2
    To write one ``\`` takes two characters, because you have to escape that single character with a second ``\``. If you need a literal two ``\\`` then use ``\\\\`` – Elliott Frisch Aug 28 '18 at 04:51
  • 1
    The double backslash is only there in the string literal. It represents a single backslash. I.e. `System.out.println("\\");` prints just a single backslash. If you get the string from somewhere else, there is no need to modify it. – Henry Aug 28 '18 at 04:51
  • 1
    Check this out https://stackoverflow.com/questions/1701839/string-replaceall-single-backslashes-with-double-backslashes – Gabriel Aug 28 '18 at 04:52

2 Answers2

1

Try doing two replacements, one to handle the filename, the other to handle the formatting of the path:

String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.replaceAll("(?<=\\\\)([^\\\\]+)$", "[$1]").replace("\\, "\\\\");
System.out.println(filepath);

C:\\Users\\Desktop\\[Sheet.xlsx]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

I have written some function. Just pass the file absolute path and you will get the your output. May it helps....

public static String pathFormat(String path) {
        System.out.println("pathFormat1...");
        String formatStr="\"";
        StringTokenizer st=new StringTokenizer(path,"\\");
        while(st.hasMoreTokens()) {
            String nextToken = st.nextToken();
            System.out.println(nextToken);
            //formatStr+=nextToken;
            if(st.hasMoreTokens()) {
                formatStr+=nextToken;
                formatStr+="\\\\";
            }
            else {
                formatStr+="[";
                formatStr+=nextToken;
                formatStr+="]\"";
            }
        }
Sai Srujan
  • 27
  • 4