java向Excel文件寫入數據


/*
使用之前要記得導入第三的jar包
這個是我之前使用的時候那別人的東西自己修改了一下 還沒來得及好好地封裝一下
還望見諒,注釋我感覺寫的挺清楚的就在不進行解釋代碼了
*/

package com.zzp.ExcelParse;

import jxl.Workbook;
import jxl.format.*;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.*;
import jxl.write.Colour;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
* 將數據存到Excel文件中
*
* Created by hasee on 2016/11/28.
*/
public class ExcelOperaation {
public void writeExcel(String path, List<String[]> list, String sheet,String[] title) {
try {
// 創建Excel工作薄
WritableWorkbook wwb = null;
// 新建立一個jxl文件
OutputStream os = new FileOutputStream(path);
wwb = Workbook.createWorkbook(os);
// 添加第一個工作表並設置第一個Sheet的名字
WritableSheet sheets = wwb.createSheet(sheet, 1);
Label label;
for (int i = 0; i < title.length; i++) {
// Label(x,y,z) 代表單元格的第x+1列,第y+1行, 內容z
// 在Label對象的子對象中指明單元格的位置和內容
// label = new Label(i, 0, title[i]);
label = new Label(i, 0, title[i], getHeader());
//設置列寬
sheets.setColumnView(i, 20);
// sheets.setColumnView(4, 100);
// 將定義好的單元格添加到工作表中
sheets.addCell(label);
}

//設置單元格屬性
WritableCellFormat wc = new WritableCellFormat();
// 設置居中
wc.setAlignment(Alignment.CENTRE);
// 設置邊框線
wc.setBorder(Border.ALL, BorderLineStyle.THIN);

for (int i = 0; i < list.size(); i++) {
String[] arrData = list.get(i);
for (int j = 0; j < arrData.length; j++) {
//向特定單元格寫入數據
//sheets.setColumnView(j, 20);
label = new Label(j, 1 + i, arrData[j], wc);
sheets.addCell(label);
}
}
// 寫入數據
wwb.write();
// 關閉文件
wwb.close();
} catch (Exception e) {
e.printStackTrace();
return ;
}
}
public static WritableCellFormat getHeader() {
// 定義字體
WritableFont font = new WritableFont(WritableFont.TIMES, 10,
WritableFont.BOLD);
try {
// 黑色字體
font.setColour(jxl.format.Colour.BLACK);
} catch (WriteException e1) {
e1.printStackTrace();
}
WritableCellFormat format = new WritableCellFormat(font);
try {
// 左右居中
format.setAlignment(jxl.format.Alignment.CENTRE);
// 上下居中
format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
// 黑色邊框
format.setBorder(Border.ALL, BorderLineStyle.THIN, jxl.format.Colour.BLACK);
// 黃色背景
format.setBackground(jxl.format.Colour.YELLOW);
} catch (WriteException e) {
e.printStackTrace();
}
return format;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM