我正在开发一个写入 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 个字符长的空格。
如果有任何帮助,我将不胜感激!
最佳答案
真正的答案是 Sheet.setColumnWidth(int index, int width)
将列的列设置为 width*256。您的断言是正确的,索引是从零开始的列号。宽度以字符的 1/256 指定。
关于java - HSSF 改变列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37552453/