javaExcel⾃动调整列宽在开发中经常需要⽤到对Excel⽂件的操作,现在根据⽹上的资料整理如下:
import java.io.FileOutputStream;
import org.apache.poi.hssf.urmodel.HSSFCell;
import org.apache.poi.hssf.urmodel.HSSFCellStyle;
import org.apache.poi.hssf.urmodel.HSSFFont;
保持联络crazy的意思import org.apache.poi.hssf.urmodel.HSSFRow;
import org.apache.poi.hssf.urmodel.HSSFSheet;
import org.apache.poi.hssf.urmodel.HSSFWorkbook;
import org.apache.poi.hssf.urmodel.HSSFRichTextString;
import org.apache.poi.hssf.urmodel.HSSFDataFormat;
import org.apache.poi.hssf.urmodel.HSSFComment;
import org.apache.poi.hssf.urmodel.HSSFPatriarch;
import org.apache.poi.hssf.urmodel.HSSFClientAnchor;
public class PoiCreateExcelTest {
public static void main(String[] args) {
/**
* @e <a href="poi.apache/hssf/quick-guide.html#NewWorkbook">For more</a>
*/
// 创建新的Excel ⼯作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel⼯作簿中建⼀⼯作表,其名为缺省值, 也可以指定Sheet名称
HSSFSheet sheet = ateSheet();
/jad
/HSSFSheet sheet = ateSheet("SheetName");
// ⽤于格式化单元格的数据
HSSFDataFormat format = ateDataFormat();
// 创建新⾏(row),并将单元格(cell)放⼊其中. ⾏号从0开始计算.
HSSFRow row = ateRow((short) 1);
// 设置字体
HSSFFont font = ateFont();
亲爱的英文是什么font.tFontHeightInPoints((short) 20); //字体⾼度
font.tColor(HSSFFont.COLOR_RED); //字体颜⾊
font.tFontName("⿊体"); //字体
font.tBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //宽度
font.tItalic(true); //是否使⽤斜体
// font.tStrikeout(true); //是否使⽤划线
上海上南中学// 设置单元格类型
HSSFCellStyle cellStyle = ateCellStyle();
cellStyle.tFont(font);
cellStyle.tAlignment(HSSFCellStyle.ALIGN_CENTER); //⽔平布局:居中
cellStyle.tWrapText(true);
// 添加单元格注释
// 创建HSSFPatriarch对象,HSSFPatriarch是所有注释的容器.
HSSFPatriarch patr = ateDrawingPatriarch();
新东方托福网络课堂// 定义注释的⼤⼩和位置,详见⽂档
HSSFComment comment = ateComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
// 设置注释内容
comment.tString(new HSSFRichTextString("可以在POI中添加注释!"));
// 设置注释作者. 当⿏标移动到单元格上是可以在状态栏中看到该内容.
comment.tAuthor("Xuys.");
// 创建单元格
HSSFCell cell = ateCell((short) 1);
HSSFRichTextString hssfString = new HSSFRichTextString("Hello World!");
cell.tCellValue(hssfString);//设置单元格内容
cell.tCellStyle(cellStyle);//设置单元格样式
cell.tCellType(HSSFCell.CELL_TYPE_STRING);//指定单元格格式:数值、公式或字符串
cell.tCellComment(comment);//添加注释
//格式化数据
草莓族
酷学酷玩row = ateRow((short) 2);
cell = ateCell((short) 2);
cell.tCellValue(11111.25);
cellStyle = ateCellStyle();
cellStyle.Format("0.0"));
cell.tCellStyle(cellStyle);
row = ateRow((short) 3);
cell = ateCell((short) 3);
cell.tCellValue(9736279.073);
cellStyle = ateCellStyle();
cellStyle.Format("#,##0.0000"));
cell.tCellStyle(cellStyle);
2212sheet.autoSizeColumn((short)0); //调整第⼀列宽度
sheet.autoSizeColumn((short)1); //调整第⼆列宽度
sheet.autoSizeColumn((short)2); //调整第三列宽度
sheet.autoSizeColumn((short)3); //调整第四列宽度
try {
FileOutputStream fileOut = new FileOutputStream("C:/3.xls"); workbook.write(fileOut);
fileOut.clo();
} catch (Exception e) {
hedp
System.out.String());
}
}
}
autoSizeColumn这个⽅法,是⾃动调整列宽的代码