写Excel
public class Demo {
public static void main(String[] args) throws IOException {
//创建一个excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个新的sheet工作表
HSSFSheet sheet = workbook.createSheet("Sheet 1");
//用于创建超链接
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
//创建行和列
for (int rowIndex = 0; rowIndex < 10; rowIndex++) {
// 创建行
HSSFRow row = sheet.createRow(rowIndex);
//此处设置第一行行高为 510(默认为255)
if (rowIndex == 0)
row.setHeight((short) 510); //设置行高
for (int columnIndex = 0; columnIndex < 10; columnIndex++) {
//此处设置 第2列 列宽 默认为2048
if (rowIndex == 0 && columnIndex == 1)
sheet.setColumnWidth(columnIndex,4096);
//创建元素
HSSFCell cell = row.createCell(columnIndex);
//为列元素设置字体
HSSFFont font = workbook.createFont();
font.setColor(IndexedColors.RED.getIndex()); // 字体颜色
HSSFCellStyle cellStyle = workbook.createCellStyle(); // 创建样式
cellStyle.setFont(font);
cell.setCellStyle(cellStyle); // 设置样式
cell.setCellValue("R" + rowIndex + ":C" + columnIndex);
//添加超链接
if (rowIndex == 0 && columnIndex == 0){
HSSFHyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("https://www.baidu.com");
cell.setHyperlink(hyperlink);
}
}
}
workbook.write(new File("Excel.xls"));
workbook.close();
}
}
读Excel
public class Demo {
public static void main(String[] args) throws IOException {
Workbook workbook = WorkbookFactory.create(new File("Excel.xls"));
//获得工作簿数目
int sheetNum = workbook.getNumberOfSheets();
//遍历工作簿
for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++) {
Sheet sheet = workbook.getSheetAt(sheetIndex);
int rowNum = sheet.getLastRowNum() + 1;
//遍历各行
for (int rowIndex = 0; rowIndex < rowNum; rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row == null)
continue;
int columnNum = row.getPhysicalNumberOfCells();
//遍历各列的元素
for (int columnIndex = 0; columnIndex < columnNum; columnIndex++) {
//获取超链接地址
Cell cell = row.getCell(columnIndex);
if (columnIndex == 0 && rowIndex == 0) {
System.out.printf("(%s) ", cell.getHyperlink().getAddress());
}
System.out.printf("%s ", row.getCell(columnIndex).getStringCellValue());
}
System.out.println();
}
}
workbook.close();
}
}