Change a String (Put brackets around file name and

2019-09-03 11:45发布

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.

2条回答
霸刀☆藐视天下
2楼-- · 2019-09-03 12:24

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]
查看更多
疯言疯语
3楼-- · 2019-09-03 12:32

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+="]\"";
            }
        }
查看更多
登录 后发表回答