我正在做一个可以写入excel文件的项目。我正在使用HSSF POI。我的代码在写入excel文件时工作得很好,但是在格式化方面有问题。我想让每个列都有一个特定的宽度。我为此做了研究,并确信我完全遵循了所描述的内容,但是单元在运行时不会发生变化。下面是我的代码:
测试类
package mainClass;
import parsing.WriteExcel;
public class TestClass
{
public static void main(String args[]){
WriteExcel wExcel = new WriteExcel();
wExcel.writeExcel();
}
}编写类
package parsing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javafx.scene.control.Cell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class WriteExcel
{
private static final String FILE_PATH = "C:\\Users\\jhamric\\Documents\\PainDifferences.xls";
public void writeExcel(){
ArrayList<String> sample1 = new ArrayList<String>();
ArrayList<String> sample2 = new ArrayList<String>();
sample1.add("1");
sample1.add("2");
sample2.add("a");
sample2.add("b");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Unmatched Transactions");
sheet.setColumnWidth(1, 25);
HSSFFont fontBold = workbook.createFont();
fontBold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle styleBold = workbook.createCellStyle();
styleBold.setFont(fontBold);
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("0",new Object[]{"Number","Letter"});
//for(int i = 0; i < ParseFiles.InstrId.size(); i++){
for(int i = 0; i < sample1.size(); i++){
String currentIString = Integer.toString(i+1);
data.put(currentIString, new Object[]{sample1.get(i),sample2.get(i)});
//data.put(currentIString, new Object[]{ParseFiles.InstrId.get(i)});
}
Set<String> keyset = data.keySet();
int rownum = 0;
for(String key: keyset){
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for(Object obj : objArr){
org.apache.poi.ss.usermodel.Cell cell = row.createCell(cellnum++);
if(cell.toString().equals("Number")){
cell.setCellStyle(styleBold);
}
cell.setCellValue((String)obj);
}
}
try{
FileOutputStream out = new FileOutputStream(new File(FILE_PATH));
workbook.write(out);
out.close();
workbook.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}具体地说,我在这里声明了设置列宽的代码:
sheet.setColumnWidth(1, 25);我的理解是,第一个数字是索引(所以它实际上是第二列),第二个数字是字符长度,所以列中的所有单元格都应该是25个字符长度的空格。
我将非常感谢在这方面的任何帮助!
发布于 2016-06-01 02:01:34
我发现了问题所在。
该值实际上不是字符数,而是其他值。我尝试了5000,它正确地调整了列的大小。
发布于 2016-06-01 19:02:20
真正的答案是Sheet.setColumnWidth(int index, int width)将列的宽度设置为*256。索引是从零开始的列号的断言是正确的。宽度以字符的1/256指定。
发布于 2020-06-22 15:38:16
要将宽度设置为25个字符,需要传递(1,25 * 256)
https://stackoverflow.com/questions/37552453
复制相似问题