所以我想要完成的是在列的每个单元格下写一个数据数组,以获得尽可能多的数组元素。我希望我在excel中也看起来像这样:
buyer | parts | price| quantity | comments
tom | blah | 546 | 5 | blah
| blah | 56 | 67 |
我的文件列数量多于此数,但我想举一个简短的例子。什么也造成我的问题是,我不想打印作者在完成我的阵列数据集后最后一行上的下一列,所以我希望它在那个forst线上。我已经调查过其他图书馆来完成这项任务,但我找不到任何可以满足我需求的东西。我明白CSV文件的性质可能不允许这种情况发生,没有手动添加空白单元格,但有没有其他方法可以做到这一点?
Enumeration <String> paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName = (String)paramNames.nextElement();
writer.append(paramName);
writer.append(',');
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1)
{
String paramValue = paramValues[0];
if (paramValue.length() == 0)
{
writer.append("No Value");
writer.append('\n');
}
else
{
writer.append(paramValue);
writer.append('\n');
}
}
else
{
for(int i = 0; i<paramValues.length; i++)
{
writer.append(paramValues[i]);
writer.append(',');
}
writer.append('\n');
}
previousname = paramName;
}
writer.flush();
writer.close();
}
还要澄清这些数据的来源,一个位于表单中间的JSP表,所以我正在读取表中的值数组。
答案 0 :(得分:1)
来自:http://javacodeonline.blogspot.ca/2009/09/java-code-to-write-to-csv-file.html
/** The below Java Code writes
* some data to a file in CSV
* (Comma Separated Value) File
*/
package developer;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class MakeCSVFile {
public static void main(String[] args) throws IOException {
//Note the "\\" used in the path of the file
//instead of "\", this is required to read
//the path in the String format.
FileWriter fw = new FileWriter("D:\\JavaCodeFile\\WriteTest.csv");
PrintWriter pw = new PrintWriter(fw);
//Write to file for the first row
pw.print("Hello guys");
pw.print(",");
pw.print("Java Code Online is maing");
pw.print(",");
pw.println("a csv file and now a new line is going to come");
//Write to file for the second row
pw.print("Hey");
pw.print(",");
pw.print("It's a");
pw.print(",");
pw.print("New Line");
//Flush the output to the file
pw.flush();
//Close the Print Writer
pw.close();
//Close the File Writer
fw.close();
}
}
可能不是做硬打印而是做一个数组循环并打印用逗号分隔的每个值。
类似的东西:
Array array;
Iterator<String> iter = array.iterator();
while (iter.hasNext())
{
object = iter.next();
pw.print(object.getBuyer());
pw.print(",");
pw.print(object.getTitle());
..
}
答案 1 :(得分:0)
如果您使用Java编写CSV文件,请考虑使用OpenCSV库。