📄 writetoexcel.java
字号:
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class WriteToExcel {
public static void main(String[] args) throws IOException {
//创建Excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(0,"学生分数一览表", HSSFWorkbook.ENCODING_UTF_16);
// 设置单元格字体、字号、加粗、边框
HSSFFont font = workbook.createFont();
font.setFontName("隶书");
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setFont(font);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//第1行,标题文字
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellStyle(cellStyle);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("学号");
cell = row.createCell((short) 1);
cell.setCellStyle(cellStyle);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("姓名");
cell = row.createCell((short) 2);
cell.setCellStyle(cellStyle);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("总分");
//第2行
row = sheet.createRow(1);
cell = row.createCell((short) 0);
cell.setCellStyle(cellStyle);
cell.setCellValue("001");
cell = row.createCell((short) 1);
cell.setCellStyle(cellStyle);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("张三");
cell = row.createCell((short) 2);
cell.setCellStyle(cellStyle);
cell.setCellValue("256");
//第3行
row = sheet.createRow(2);
cell = row.createCell((short) 0);
cell.setCellStyle(cellStyle);
cell.setCellValue("002");
cell = row.createCell((short) 1);
cell.setCellStyle(cellStyle);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("李四");
cell = row.createCell((short) 2);
cell.setCellStyle(cellStyle);
cell.setCellValue("216");
//第4行
row = sheet.createRow(3);
cell = row.createCell((short) 0);
cell.setCellStyle(cellStyle);
cell.setCellValue("003");
cell = row.createCell((short) 1);
cell.setCellStyle(cellStyle);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("王二麻子");
cell = row.createCell((short) 2);
cell.setCellStyle(cellStyle);
cell.setCellValue("266");
// 写入文件
FileOutputStream fileOutput = new FileOutputStream("d:/test.xls");
workbook.write(fileOutput);
fileOutput.flush();
fileOutput.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -