Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - How to remove the carriage return from string while pasting content to Excel file

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 ( ) 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 for line breaks and not just . I tried to replace my with 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
b1";
      String   tmpString =myString.replace("
","
");
      System.out.println( "Original = " +"""+myString+""");
      System.out.println( "Result   = " +"""+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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
is a test";
    String s2 = s1.replaceAll("[

]", "");
    System.out.println(s2);
} 

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...