简体   繁体   English

将括号放在文件名周围

[英]Put Brackets around filename

This is a correction of my previous question Put brackets around filename for Excel formula 这是我刚才的问题的纠正 在方括号内文件名的Excel公式

My project is based on Apache POI.I'm trying to use a formula on a cell. 我的项目基于Apache POI,我正在尝试在单元格上使用公式。 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. 我使用的是JFileChooser,它允许用户选择文件。 Therefore the filepath will be changed every time the program is used. 因此,每次使用该程序时,文件路径都会更改。

From the JFileChooser, I'm getting a filepath as follows. 从JFileChooser,我得到一个文件路径,如下所示。

 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? 如何更改从JFileCHooser获取的字符串以正确运行公式?

In previous question, I mistakenly typed C:\\Users\\Desktop[Sheet.xlsx] instead of C:\\Users\\Desktop\\[Sheet.xlsx] The answers gave me the output which i've mentioned. 在上一个问题中,我错误地键入了C:\\ Users \\ Desktop [Sheet.xlsx]而不是C:\\ Users \\ Desktop \\ [Sheet.xlsx]答案给出了我提到的输出。 But I need the Output as C:\\Users\\Desktop\\[Sheet.xlsx] 但是我需要输出为C:\\Users\\Desktop\\[Sheet.xlsx]

Please help. 请帮忙。

If you want to solve this by directly altering the file path, you may use String#replaceAll : 如果要通过直接更改文件路径来解决此问题,则可以使用String#replaceAll

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

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

Demo 演示版

File names won't have \\backslashes in them, so we can assume that our filename begins after the last backslash and ends at the end of the string. 文件名中不会带有\\反斜杠,因此我们可以假定文件名在最后一个反斜杠之后开始,并在字符串末尾结束。

We can use this: 我们可以这样使用:

String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
String dir = filepath.substring(0, filepath.lastIndexOf("\\"+1));
String filename = filepath.substring(filepath.lastIndexOf("\\"+1));

filepath = dir + "[" + filename + "]";

Or a shorter version: 或更短的版本:

String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath =  filepath.substring(0, filepath.lastIndexOf("\\"+1)) +
            "[" + filepath.substring(filepath.lastIndexOf("\\"+1)) + "]";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM