1. 使用POI类库,设置excel列宽度
在使用NPOI技术开发自动操作EXCEL软件时遇到不能精确设置列宽的问题。
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
sheet1.SetColumnWidth(0, 50 * 256); // 在EXCEL文档中实际列宽为49.29
sheet1.SetColumnWidth(1, 100 * 256); // 在EXCEL文档中实际列宽为99.29
sheet1.SetColumnWidth(2, 150 * 256); // 在EXCEL文档中实际列宽为149.29
如果以上兼容性有问题,可以使用以下方式:
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
sheet1.SetColumnWidth(0, (int)((50 + 0.72) * 256)); // 在EXCEL文档中实际列宽为50
sheet1.SetColumnWidth(1, (int)((100 + 0.72) * 256)); // 在EXCEL文档中实际列宽为100
sheet1.SetColumnWidth(2, (int)((150 + 0.72) * 256)); // 在EXCEL文档中实际列宽为150
即在要设置的实际列宽中加上列宽基数:0.72
2. 设置高度自适应
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.regex.Pattern;
/**
* @author steve
* @Description
* @date 2022/3/3 17:34
*/
public class ExcelAutoHeightUtil {
public static void main(String[] args) throws IOException {
InputStream is = null;
Workbook book = null;
is = new FileInputStream("D:\\test.xlsx");
book = new XSSFWorkbook(is);
Sheet sheetAt = book.getSheetAt(0);
//使用方法
float hieght = getExcelCellAutoHeight("测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容", 8f);
//根据字符串的长度设置高度
Row row = sheetAt.getRow(sheetAt.getLastRowNum());
row.setHeightInPoints(hieght);
File f = new File("D:\\test.xlsx");
FileOutputStream out = new FileOutputStream(f);
book.write(out);
out.close();
}
//str 是单元格需要放入的 字符串 fontCountInline 是该单元格每行多少个汉字 全角为1 英文或符号为0.5
public static float getExcelCellAutoHeight(String str, float fontCountInline) {
float defaultRowHeight = 12.00f;//每一行的高度指定
float defaultCount = 0.00f;
for (int i = 0; i < str.length(); i++) {
float ff = getregex(str.substring(i, i + 1));
defaultCount = defaultCount + ff;
}
return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;//计算
}
public static float getregex(String charStr) {
if(charStr==" ")
{
return 0.5f;
}
// 判断是否为字母或字符
if (Pattern.compile("^[A-Za-z0-9]+$").matcher(charStr).matches()) {
return 0.5f;
}
// 判断是否为全角
if (Pattern.compile("[\u4e00-\u9fa5]+$").matcher(charStr).matches()) {
return 1.00f;
}
//全角符号 及中文
if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) {
return 1.00f;
}
return 0.5f;
}
}