问题描述
当我将由Java代码生成的内容(或文本)粘贴到Excel中时,我有问题。
问题是我的Java代码生成一个包含多行的字符串,即包含换行符( \\\
)。当我尝试复制这个内容并将其粘贴到Excel文件中时,我得到一个带有方块符号的多行文本。我知道Windows使用
\r\\\
进行换行符,而不仅仅是
\\\
。我试图用
\r\\\
替换我的
\\\
并粘贴生成的文本,但我是在我的Excel文件中获得相同的方框。这是我的示例代码:
I have a problem while pasting my contents (or text) generated by Java code into excel.The problem is that my Java code generates a String with multiple lines, i.e. with line breaks (\n
) included. When I try to copy this content and paste it into an Excel file, I am getting a multiline text with a square box symbol. I came to know that Windows uses \r\n
for line breaks and not just \n
. I tried to replace my \n
with \r\n
and paste the generated text, but I am getting the same square boxes in my Excel file. Here is my sample code:
String myString = "a1\nb1";
String tmpString =myString.replace("\n","\r\n");
System.out.println( "Original = " +"\""+myString+"\"");
System.out.println( "Result = " +"\""+tmpString+"\"");
我使用包装文本。当我尝试在Excel中粘贴 tmpstring 时,我收到了方框。如何在单元格中使用多行删除框??
I have used the " " to wrap the text. When I tried to paste tmpstring in Excel, I got the square box. How can I remove the boxes with multiple lines in my cell?
推荐答案
返回/换行,还是不要?您的标题表示您没有,当字符串有换行时,您的代码显式添加回车符。如果你想摆脱两者,使用String.replaceAll(),它需要一个正则表达式:
Do you want the carriage return / newline, or don't you? Your title says that you don't, your code is explicitly adding carriage returns when the string has a newline. If you want to get rid of both, use String.replaceAll(), which takes a regex:
public static void main(String[] argv)
throws Exception
{
String s1 = "this\r\nis a test";
String s2 = s1.replaceAll("[\n\r]", "");
System.out.println(s2);
}
此示例查找字符的任何出现,并删除它们。你可能想要查找字符序列并替换为一个空格,但是我会留下你的看法:查看的文档java.util.regex.Pattern
。
This example finds any occurrence of the characters, and deletes them. You probably want to look for the sequence of characters and replace with a space, but I'll leave that up to you: look at the doc for java.util.regex.Pattern
.
我怀疑盒子是其他一些字符,而不是返回或换行。
And I suspect that the "box" is some other character, not a return or newline.
这篇关于如何在将内容粘贴到Excel文件时从字符串中删除回车符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!