标签:java 案例 rowIndex Excel columnIndex int workbook sheet row
写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();
}
}
标签:java,案例,rowIndex,Excel,columnIndex,int,workbook,sheet,row 来源: https://blog.csdn.net/weixin_41618135/article/details/113199795
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。