所以我想要完成的是为我拥有的尽可能多的数组元素在列的每个单元格中写入一个数据数组。我希望我在 Excel 中也看起来像这样:
buyer | parts | price| quantity | comments
tom | blah | 546 | 5 | blah
| blah | 56 | 67 |
我的文件有比这更多的列,但我想举一个简短的例子。造成我问题的另一个原因是,一旦完成我的数组数据集,我不想在编写器所在的最后一行上打印下一列,所以我希望它位于第一行。我已经研究过其他库来完成此任务,但我找不到任何可以满足我需求的库。我确实了解 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 表,因此我正在读取表中的值数组。
最佳答案
来自: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());
..
}
关于java - 在java中将字符串数组写入csv文件的一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11745529/