Java 는 poi 구성 요소 로 Excel 형식 데 이 터 를 내 보 냅 니 다.
14325 단어 JavaExcel데이터 내 보 내기
자바 에 서 는 엑셀 에 대한 지원 이 JXL,POI 등 여러 가지 가 있다.제 가 사용 하 는 것 은 POI 에서 엑셀 작업 을 하 는 것 입 니 다.다음은 POI 구성 요소 의 사용 과 제 가 사용 하 는 도구 류 를 간단하게 공유 하 겠 습 니 다.
POI 구성 요소
poi 구성 요 소 는 아파 치가 제공 하 는 구성 요소 패키지 입 니 다.주요 직책 은 자바 프로그램 에 office 문서 에 대한 작업 을 제공 하 는 것 입 니 다.본 고 는 주로 엑셀 조작 에 대한 소개 이다.
공식 홈 페이지:http://poi.apache.org/index.html
API 문서:http://poi.apache.org/apidocs/index.html
POI 구성 요소 기본 소개
사용 할 때 우 리 는 poi 구성 요소 가 우리 에 게 제공 하 는 엑셀 작업 과 관련 된 종 류 는 모두 HSSF 로 시작 하 는 것 을 발견 할 수 있 습 니 다.이런 종 류 는 주로 org.apache.pai.hssf.usermodel 이 가방 아래 에 있 습 니 다.엑셀 과 같은 대상,셀 의 스타일,글꼴 스타일 과 부분의 도구 류 가 포함 되 어 있 습 니 다.우리 가 자주 사용 하 는 몇 가지 종 류 를 소개 합 니 다.
1.HSSFWorkbook'Excel 파일 대상'만 들 기
// Excel
HSSFWorkbook workbook = new HSSFWorkbook();
2.워 크 북 대상 을 사용 하여 워 크 시트 대상 만 들 기
//
HSSFSheet sheet = workbook.createSheet(" ");
3.줄 과 작업 셀 대상 만 들 기
// HSSFRow ( )
HSSFRow row = sheet.createRow(0);
// HSSFCell ( )
HSSFCell cell=row.createCell(0);
//
cell.setCellValue(" ");
4.Excel 파일 저장
// Excel
FileOutputStream output=new FileOutputStream("d:\\workbook.xls");
workbook.write(output);
output.flush();
맞 춤 형 내 보 내기 스타일 설정여기 제 가 자주 사용 하 는 스타일 설정 방법 을 열거 하 겠 습 니 다!
1.셀 을 합 쳐 너비,높이 설정
//
HSSFCellStyle cellStyle = workbook.createCellStyle();
//
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
//
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// ---
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);
// ( )
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
//
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
//
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);
//
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);
//
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//
cell.setCellStyle(cellStyle);
//
row.setRowStyle(cellStyle);
2.셀 스타일 설정
//
HSSFCellStyle cellStyle = workbook.createCellStyle();
//
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
//
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// ---
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);
// ( )
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
//
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
//
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);
//
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);
//
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//
cell.setCellStyle(cellStyle);
//
row.setRowStyle(cellStyle);
3.글꼴 설정
//
HSSFFont fontStyle = workbook.createFont();
//
fontStyle.setFontName(" ");
//
fontStyle.setFontHeightInPoints((short)12);
//
font.setColor(HSSFColor.BLUE.index);
//
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//
font.setItalic(true);
//
font.setUnderline(HSSFFont.U_SINGLE);
//
cellStyle.setFont(font);
개인 용도다음은 개인의 전체적인 사용 과정 을 공유 하 겠 습 니 다!
처리 액 션
//
List<PBillBean> dataset = new ArrayList<PBillBean>();
// dataset
for (int i = 0; i < 10; i++) {
PBillBean bean = new PBillBean();
dataset.add(bean);
}
//
File tempFile = null;
try {
//Excel
ExportExcel<PBillBean> ex = new ExportExcel<PBillBean>();
//
String[] headers = { " 1", " 2", " 3", " 4", " 5", " 6" };
//
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//
String filename = "bill_" + format.format(new Date()) + ".xls";
//
String rootDir = request.getSession().getServletContext().getRealPath("/");
//
String path = rootDir + File.separator + "tempfile";
File saveDir = new File(path);
if (!saveDir.exists()) {
saveDir.mkdirs();//
}
//
path = path + File.separator + filename;
tempFile = new File(path); //
//
OutputStream out = new FileOutputStream(tempFile);
// Excel
HSSFWorkbook workbook = new HSSFWorkbook();
//
String[] sheetNames = { " " };
for (int i = 0; i < sheetNames.length; i++) {
workbook.createSheet(sheetNames[i]);
}
// Excel
ex.exportExcel(sheetNames[0], headers, dataset, out,
"yyyy-MM-dd HH:mm", workbook);
try {
//
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
out.close();
// 。
BufferedInputStream fis = new BufferedInputStream(
new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// response
response.reset();
// response Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes()));
response.addHeader("Content-Length", "" + tempFile.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=utf-8");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (tempFile != null && tempFile.exists()) {
tempFile.delete();//
}
}
Excel 도구 클래스 내 보 내기
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,HSSFWorkbook workbook)
{
//
HSSFSheet sheet = workbook.getSheet(title);
// 15
sheet.setDefaultColumnWidth((short) 15);
//
HSSFCellStyle style = workbook.createCellStyle();
//
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//
style.setFont(font);
//
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//
style2.setFont(font2);
//
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// ,
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
//
comment.setString(new HSSFRichTextString(" POI !"));
// , .
comment.setAuthor("leno");
//
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// ,
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext())
{
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// , javabean , getXxx()
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try
{
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
//
String textValue = null;
if (value instanceof Boolean)
{
boolean bValue = (Boolean) value;
textValue = " ";
if (!bValue)
{
textValue = " ";
}
}
else if (value instanceof Date)
{
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
}
else if (value instanceof byte[])
{
// , 60px;
row.setHeightInPoints(60);
// 80px,
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}
else
{
//
textValue = value == null? "": value.toString();
}
// , textValue
if (textValue != null)
{
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches())
{
// double
cell.setCellValue(Double.parseDouble(textValue));
}
else
{
HSSFRichTextString richString = new HSSFRichTextString(textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
finally
{
//
}
}
}
}
작은 매듭Excel 데이터 의 내 보 내기 가 큰 성 과 를 거 두 었 습 니 다.개인 적 으로 이 내 보 내기 도구 류 가 좋 은 것 같 습 니 다.여러분 들 이 좋아 하 시 기 를 바 랍 니 다!
자바 에서 poi 구성 요 소 를 사용 하여 Excel 형식 데 이 터 를 내 보 내 는 것 에 대한 더 많은 글 은 아래 링크 를 보십시오.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.