how to simulate Excel control codes in String - java

One web project I'm involved in requires generating a CSV to the user.
One field is notes and there can be multiple notes in the field, separated by a return (alt-enter in Excel), appearing as
A USER entered on 02/17/2023: Test note
A USER entered on 02/17/2023: This is another note
Is it possible to insert control codes into a Java string that Excel will pick up and format the cell properly?
For what it's worth, this was my attempt:
}else if (formType.equalsIgnoreCase("downloadCSV")) {
Date d = new Date();
String filename = "C:/temp/rtTmp" + d.getTime() + ".csv";
File f = new File(filename);
List<Contact> contactList = RetentionTrackDatabaseUtil.getContacts();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("name,"
+ "gender,"
+ "age,"
+ "DOB,"
+ "DOH,"
+ "DOR,"
+ "DOS,"
+ "dateContact,"
+ "reason,"
+ "status,"
+ "empNum,"
+ "shift,"
+ "phone,note(s)\n");
for (Contact c : contactList) {
System.out.println(c.getAge());
bw.append("\"" + c.getName() + "\"" + ","
+ c.getGender() + ","
+ Integer.toString(c.getAge()) + ","
+ (c.getDOB()!=null?RetentionTrackUtil.sdf.format(c.getDOB()):"") + ","
+ (c.getDOH()!=null?RetentionTrackUtil.sdf.format(c.getDOH()):"") + ","
+ (c.getDOR()!=null?RetentionTrackUtil.sdf.format(c.getDOR()):"") + ","
+ (c.getDOS()!=null?RetentionTrackUtil.sdf.format(c.getDOS()):"") + ","
+ (c.getDateContact()!=null?RetentionTrackUtil.sdf.format(c.getDateContact()):"") + ","
+ c.getReason() + ","
+ c.getStatus() + ","
+ c.getEmpNum() + ","
+ c.getShift() + ","
+ c.getPhone() + ",");
for(Note n: c.getNoteList()){
bw.append("(" + n.getEnteredBy() + " on " + RetentionTrackUtil.sdf.format(n.getNoteDate()) + ")" + n.getNote() + "\\n");
}
bw.append("\n");
}
bw.close();
sendFile(response, filename);
}

Related

Query Creation Does Not Print All Indexes

When I create the file and write in the query, does it write only once? why?
for (spinelliIndex = 0; spinelliIndex < spinelli.getVeicoli_id().size(); spinelliIndex++) {
boolean match = false;
for (veicoloIndex = 0; veicoloIndex < veicoloDb.getVeicoloId().size(); veicoloIndex++) {
if (spinelli.getVeicoli_targa().get(spinelliIndex).equals(veicoloDb.getTarga().get(veicoloIndex))) {
match = true;
// Stampa a Video
System.out.println(spinelli.getVeicoli_targa().get(spinelliIndex) + " = "
+ veicoloDb.getTarga().get(veicoloIndex) + " --> "
+ spinelli.getVeicoli_id().get(spinelliIndex) + " --> "
+ veicoloDb.getVeicoloId().get(veicoloIndex));
// Scrivi nella riga i
row = sheet.getRow(spinelliIndex);
// Scrivi nella colonna AC indice 28
cell = row.createCell(28);
// Scrivi il ciclo in tutte le righe nella colonna AC indice 28
sheet.getRow(spinelliIndex).createCell(28)
.setCellValue(spinelli.getVeicoli_id().get(spinelliIndex));
FileOutputStream fos = new FileOutputStream(filePath);
// Scrivi nel file EXCEL
wb.write(fos);
fos.close();
// Scrivi NEl file .txt
// Crea la Query e scrivi nel file
file = new File(path);
fw = new FileWriter(file);
fw.write("UPDATE veicolo SET ID = " + "'" + spinelli.getVeicolo_newid().get(spinelliIndex) + "'" + ","
+ "CREATE_DATE = " + "'" + veicoloDb.getCreate_date().get(veicoloIndex) + "'" + ","
+ "MODIFIED_DATE = " + "'" + veicoloDb.getModified_date().get(veicoloIndex) + "'" + "," + "UUID = "
+ "'" + veicoloDb.getUuid().get(veicoloIndex) + "'" + "," + "CLASSE_EURO = " + "'"
+ veicoloDb.getClasse_euro().get(veicoloIndex) + "'" + "," + "CODICE_CLIENTE_ORIGINARIO = " + "'"
+ veicoloDb.getCodice_cliente_originario().get(veicoloIndex) + "'" + "," + "CONTRATTO = " + "'"
+ veicoloDb.getContratto().get(veicoloIndex) + "'" + "," + "DATA_FINE_VALIDITA = " + "'"
+ veicoloDb.getData_fine_validita().get(veicoloIndex) + "'" + "," + "DATA_INIZIO_VALIDITA = " + "'"
+ veicoloDb.getData_inizio_validita().get(veicoloIndex) + "'" + "," + "DISPONIBILITA = " + "'"
+ veicoloDb.getDisponibilita().get(veicoloIndex) + "'" + "," + "NAZIONE = " + "'"
+ veicoloDb.getNazione().get(veicoloIndex) + "'" + "," + "TARGA = " + "'" + veicoloDb.getTarga().get(veicoloIndex)
+ "'" + "," + "TIPO_DI_POSSESSO = " + "'" + veicoloDb.getTipo_di_possesso().get(veicoloIndex) + "'"
+ "," + "ID_ANAGRAFICA = " + "'" + veicoloDb.getId_anagrafica().get(veicoloIndex) + "'"
+ "FROM DISPOSITIVO_VEICOLO WHERE dispositivo_veicolo.id_anagrafica = veicolo.id_anagrafica"
+ ";" + "\n");
fw.flush();
fw.close();
}
}
// Targhe non trovate
if (!match) {
System.out.println("Targa non trovata: " + spinelli.getVeicoli_targa().get(spinelliIndex));
}
}
}
I'm not sure what is your expected behavior on your program, but I guess you want to write(append) your file multiple times, right?
In your code, create new file (new File()) and close the writer (fw.close()) in the loop.
It looks, the program overwrite to the same file multiple times.
So, if you want to append(not overwrite), I recommend you to put file creation and file closing on the outside of the loop like the following (dummy code):
file = new File(path);
fw = new FileWriter(file);
for (spinelliIndex = 0; spinelliIndex < spinelli.getVeicoli_id().size(); spinelliIndex++) {
fw.write("something");
}
fw.close();
Also, fw.close() will call fw.flush(). If you don't have any specific reason to write it, you can remove it.

.txt array out from user input

I have since updated this code per suggestions for this forum. I am still confused as to how to get my .txt file selection to out print all instances of the name entered. my file in which all my .txt files are contained is named, namesbystate. To access this and all instances of the names entered are where I am getting issues. I am wondering if I replace myFile with namesbystate as a pathway extension or not?
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
// Scanner variable set up to intake user input for state selection and person's name
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
// nextLine variable now has the line from the file in it that matches the name the person input
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
}
}
} catch(FileNotFoundException e) {
System.out.print(e.getMessage());
}
}
}
Something like this will get you to where you want to be. I do not have the format of your state text files so I couldn't write the full program for you
(Edit - I just changed the code slightly. Instead of sc.next(), I should have written sc.nextLine(). The following program runs successfully with that edit):
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
//nextLine variable now has the line from the file in it that matches the name the person input so you need to parse that line and do something with it
}
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
}
}

Formatting a return string

I am trying to format this return string to display ratings at one decimal place.
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : getRating()) + "): " + numOfDeaths + " deaths");
I keep getting an error saying too few parameters passed.
You want java.text.DecimalFormat.
DecimalFormat df = new DecimalFormat("0.0##");
String result = df.format(getRating());
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : result) + "): " + numOfDeaths + " deaths");

Output on new line WITHOUT for loop

I am trying to output arrays on a new line through a basic client, server application. However, to accomplish this I have had to use substring to find the # after each word to signal the end of the line. However I want to remove this function and have each section on a new line.
public ClientHandler(Socket socket,Users newUser, int newClientUser)
throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(
client.getOutputStream(),true);
user = newUser;
clientUser = newClientUser;
String[] itemName = {user.getItemName(1), user.getItemName(2)};
String[] description = {user.getItemDescription(1), user.getItemDescription(2)};
String[] itemtime = {user.getItemTime(1), user.getItemTime(2)};
output.println(itemName[0] + "#" + itemName[1]
+ "#" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"#"+ itemName[1] +": "+description[1]+
"#"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "#" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"#");
}
private synchronized void getMessage(String response)
{
String message="";
for(int i= count; !response.substring(i, i+1).equals("#"); i++)
{
count = i;
}
}
output.println(itemName[0] + "\n" + itemName[1]
+ "\n" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"\n"+ itemName[1] +": "+description[1]+
"\n"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "\n" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"\n");
Instead of having a "#" signify a new line, you can use "\n". Java will read that from your string as a new line.

How to write a carriage return into xls file in Java

I would like to insert a carriage return into a cell of a xls file.
So I have written this code
address = rs.getString(16) + " " + rs.getString(17) + "
"
+ rs.getString(18) + " " + rs.getString(19) + " (" +
rs.getString(20) + ")";
"writer.write("<ss:Cell><ss:Data ss:Type=\"String\">" + address + "</ss:Data></ss:Cell>");`
but in the Excel File the result is that the carriage return is replaced with a "square symbol". In which mode can I resolve this issue?
Thanks,
Stefano
In excel, to enter a new line in a cell, you need to insert ASCII characters 13 + 10 (constant CrLf on this page : http://msdn.microsoft.com/en-us/library/f63200h0%28v=vs.80%29.aspx).
Have you tried:
String crLf = Character.toString((char)13) + Character.toString((char)10);
address = rs.getString(16) + " " + rs.getString(17) + crLf
+ rs.getString(18) + " " + rs.getString(19) + " (" +
rs.getString(20) + ")";

Categories

Resources