javaexcel模板
‘壹’ java POI 导出 EXCEL模板 怎么设置单元格格式为 文字
参考代码 public static void createColHeader(HSSFSheet sheet, CellStyle cellStyle,String[] columHeader) {if (sheet != null) { sheet.setDefaultColumnWidth(20); HSSFRow row = sheet.createRow(0); for (int i = 0; i < columHeader.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(columHeader[i]); if (cellStyle != null) { cell.setCellStyle(cellStyle); } } freezePane(sheet,0,1,0,1); }}
‘贰’ JAVA,Spring boot怎么据数据库数据生成Excel模板,含下拉框
只不过,jxl比较小,好用!对于下拉框联动的功能
jxl没有直接可以处理的!只能做好模板,然后用jxl往模板写数据!这样做,不完美,仅供参考02第一:excel中的联动处理
名称-定义 02设置一个区域,用来取值的区域,名称为 第一级别下拉框的选项名
第一级别 02 下拉框 数据 有效性 序列 值为 选项框 和 前面设置的区域名称相同
第二级别 02 下拉框 数据 有效性 序列 值为02=INDIRECT(B9) B9为第一级别的下拉框位置
第二:java程序的处理
A:对action进行判断 准备需要的值02filePath = CommAttachInfoFactory.rootPath
+ "/filedata/npForm/scaleTarget/模板录入模板/type-"+types[k]+".xls";
request.setAttribute("path", filePath);try{new OperationExcel().UpdateLuruExcel(filePath, temFileName,scaleTaskInfo);
} catch (Exception e) {
e.printStackTrace();}02B:具体的操作并生成文件02public void UpdateLuruExcel(String filename,String overDept,ScaleTargetForm scaleTaskInfo){try{Workbook wb = Workbook.getWorkbook(new File(filename));
WritableWorkbook workbook = Workbook.createWorkbook( new File(filename),wb);
WritableSheet sheet = workbook.getSheet(0);
sheet.addCell(new Label(0,1,scaleTaskInfo.getTask_name()+
"-"+scaleTaskInfo.getTask_start_time()));
workbook.write();
workbook.close(); }catch(Exception e){
e.printStackTrace();}}02附件为 一个做好的三级联动例子其中 选择区域的值 02可以做到另外一个sheet中,这样美观
‘叁’ java中如何导入Excel,并给出模板
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jxl.*;
public class SimUpdate {
private String fileName;
public ZfzSimUpdate(String fileName){
this.fileName = fileName;
}
static Map tNames;
static{
tNames = new HashMap();
}
/**
* 用于产生 数据库的 ID 值,组成 [年月日时分秒(100-999)] 总共 17 位数.
* 根据不同的表名,可保证同一秒内产生的 ID 号不重复
*/
private static String getDtime() {
String rid;
Date nd = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
rid = sdf.format(nd);
return rid;
}
public String getSeqNumber(String tableName) {
if(tableName == null || "".equals(tableName))
tableName = "GENERY";
Integer it;
// noinspection SynchronizeOnNonFinalField
synchronized(tNames){
it = (Integer)tNames.get(tableName);
if(it == null){
it = new Integer(100);
tNames.put(tableName, it);
}else{
if(it.intValue() > 998)
it = new Integer(100);
else
it = new Integer(1 + it.intValue());
tNames.put(tableName, it);
}
}
return getDtime() + String.valueOf(it);
}
private void updateDb(){
try{
Connection conn = DbPool.connectDB();
if(conn != null){
Statement stmt = conn.createStatement();
/**********************************************/
jxl.Workbook rwb = null;
try{
//构建Workbook对象 只读Workbook对象
//直接从本地文件创建Workbook
//从输入流创建Workbook
InputStream is = new FileInputStream(fileName);
rwb = Workbook.getWorkbook(is);
//Sheet(术语:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中
//Sheet的下标是从0开始的
//获取第一张Sheet表
Sheet rs = rwb.getSheet(0);
//获取Sheet表中所包含的总列数
int rsColumns = rs.getColumns();
//获取Sheet表中所包含的总行数
int rsRows = rs.getRows();
//获取指这下单元格的对象引用
String simNumber = "",termSeqId = "";
//指定SIM卡号及序列号
for(int i=0;i<rsRows;i++){
for(int j=0;j<rsColumns;j++){
Cell cell = rs.getCell(j,i);
if(j==0){
simNumber = cell.getContents();
}
termSeqId = "633"+simNumber;
}
String sql = "查询SQL";
int isOk = stmt.executeUpdate(sql);
if(isOk == 0 && !simNumber.equals("")){
String termId = getSeqNumber("termInf");
String insertSql = "自定义INSERT";
int isAdd = stmt.executeUpdate(insertSql);
if(isAdd > 0){
System.out.println("成功插入第"+i+"条数据");
}
}
//System.out.println("SIM卡号:"+simNumber+",序列号:"+termSeqId);
}
//以下代码为写入新的EXCEL,这里不使用,所以注释
/*
//利用已经创建的Excel工作薄创建新的可写入的Excel工作薄
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File("D://Book2.xls"),rwb);
//读取第一张工作表
jxl.write.WritableSheet ws = wwb.getSheet(0);
//获取第一个单元格对象
jxl.write.WritableCell wc = ws.getWritableCell(0, 0);
//决断单元格的类型,做出相应的转化
if (wc.getType() == CellType.LABEL) {
Label l = (Label) wc;
l.setString("The value has been modified.");
}
//写入Excel对象
wwb.write();
wwb.close();
*/
}catch(Exception e){
e.printStackTrace();
}
finally{
//操作完成时,关闭对象,翻译占用的内存空间
rwb.close();
}
/*********************************************/
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
DbPool dbPool = new DbPool("dbConn.cfg");//连接数据库
SimUpdate simUpdate = new SimUpdate("zfz_sim.xls");
simUpdate.updateDb();
}
}
‘肆’ java 往excel模板里写数,行不固定且最下面有合计,那位好点实例
嗨 你好
你可以参考一下:
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* 导出excel
* @param reportParams 导出excel列名标示
* @param list导出excel值
* @param headersexcel头
* @param reportName·excel的sheet名
* @param response
* @param startRow从哪一行开始放list值
* @param startCol 从哪一列开始放list值
* @return
*/
public boolean report(ReportBean rb, List list, XlsHeaderBean[] headers, String reportName, HttpServletResponse response, int startRow, int startCol, HttpServletRequest request){
WritableWorkbook wwb = null;
OutputStream os;
boolean flag = true;
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String strDate = format.format(date);
try {
// 用Workbook类的工厂方法创建工作薄(Workbook)对象
response.setContentType("application/x-msdownload");
String sheetName = "report";
sheetName = sheetName.replaceAll(":", "").replaceAll("[)]", "")
.replaceAll("[(]", "");
// 这里解释一下
// attachment; 这个代表要下载的,如果去掉就编程直接打开了
// filename是文件名,另存为或者下载时,为默认的文件名
response.addHeader("Content-Disposition", "attachment; filename="
+ new String(sheetName.getBytes("UTF-8"), "ISO-8859-1")+ strDate
+ ".xls");
os = response.getOutputStream();
wwb = Workbook.createWorkbook(os);
} catch (IOException e) {
e.printStackTrace();
return flag = false;
}
if (wwb != null) {
// 创建一个可写入的工作表
// Workbook的createSheet方法两个参数,1名称,2位置
WritableSheet ws = wwb.createSheet(reportName, 0);
// 下面开始添加单元格
// 导出excel
try {
Label labelC = null;
for(int j = 0; j < headers.length; j++){
if(headers[j].isUnion()){
ws.mergeCells(headers[j].getCol(), headers[j].getRow(), headers[j].getCol()+headers[j].getColLength(), headers[j].getRow()+headers[j].getRowLength());
}
labelC = new Label(headers[j].getCol(), headers[j].getRow(), headers[j].getValue());
ws.addCell(labelC);
}
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
String value = null;
for (int i = 0; i < list.size(); i++) {
Map values = (Map)list.get(i);
for (int j = 0; j < rb.getReportParams().length; j++) {
// 这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
Label labelC;
if(values.get(rb.getReportParams()[j]) == null){
value = "";
} else {
if(values.get(rb.getReportParams()[j]) instanceof java.util.Date){
value = format.format(values.get(rb.getReportParams()[j]));
} else if(values.get(rb.getReportParams()[j]) instanceof java.math.BigDecimal){
value = values.get(rb.getReportParams()[j]).toString();
} else {
value = values.get(rb.getReportParams()[j]).toString();
}
}
labelC = new Label(j+startCol, i + startRow, value);
try {
// 将生成的单元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
return flag = false;
} catch (WriteException e) {
e.printStackTrace();
return flag = false;
}
}
}
if(rb.isHasImg()){
String rootPath = this.getServletContext().getRealPath("savefiles");
String imgPath = rb.getImgPath();
if(rootPath != null && rootPath.compareTo("") != 0 && imgPath != null && imgPath.compareTo("") !=0){
String[] strs = imgPath.split("\/");
String imgName = strs[strs.length-1];
File file = new File(rootPath + File.separator + imgName);
if(file.exists()){
WritableImage wi = new WritableImage(0, startRow + list.size() + 2,12,20, file);
ws.addImage(wi);
}
}
}
try {
// 从内存中写入文件中
wwb.write();
wwb.close();
return flag;
} catch (IOException e) {
e.printStackTrace();
return flag = false;
} catch (WriteException e) {
e.printStackTrace();
return flag = false;
}
}
return flag;
}
‘伍’ java如何将数据导入Excel模板
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public static ArrayList<String> readTelExcel(String filepath) {
try {
//查询文件是否存在
File file = new File(filepath);
if (file.exists()) {
ArrayList<String> result = new ArrayList<String>();
//声明一个excel文件对象
Workbook wb = Workbook.getWorkbook(file);
//读取每一个工作薄,你也可能用wb.getSheets()得到全部工作薄
Sheet ws = wb.getSheet(0);
if (null != ws) {
//取出所有行
int rows = ws.getRows();
for (int i = 0; i < rows; i++) {
//读取第一列中的内容
String cell = ws.getCell(0, i).getContents();
if (null != cell) {
result.add(cell.trim());
}
}
}
return result;
}
return null;
} catch (BiffException e) {
e.printStackTrace();
return null;
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
‘陆’ 用Java POI到实现一个Excel模板生成。但是遇到一个比较奇特的问题。
我这边使用的时候是前台先遍历标题,再遍历内容,再传到后台,在后台手工拼的标题(如果是多行标题),再遍历。不知道你说的下拉列表功能是直接用的插件还是什么。
‘柒’ java导出excel新建行时,怎么设置样式,有一个excel的模板,但导出的数据有点多,需要在j
参考
xls.workbook.sheets(a).Range("A1:B2").Merge
这类的问题,可以打开excel,录制宏,分析宏的内容,可以找到在java中实现的办法.
‘捌’ java如何将数据导入Excel模板
下面的例子,设置了数字、日期的格式,还有字体,颜色等。
File tempFile=new File( "d:/temp/output.xls ");
WritableWorkbook workbook = Workbook.createWorkbook(tempFile);
WritableSheet sheet = workbook.createSheet( "TestCreateExcel ", 0);
//一些临时变量,用于写到excel中
Label l=null;
jxl.write.Number n=null;
jxl.write.DateTime d=null;
//预定义的一些字体和格式,同一个Excel中最好不要有太多格式
WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false, Underlinestyle.NO_UNDERLINE, jxl.format.Colour.BLUE);
WritableCellFormat headerFormat = new WritableCellFormat (headerFont);
WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false, Underlinestyle.NO_UNDERLINE, jxl.format.Colour.RED);
WritableCellFormat titleFormat = new WritableCellFormat (titleFont);
WritableFont detFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false, Underlinestyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
WritableCellFormat detFormat = new WritableCellFormat (detFont);
NumberFormat nf=new NumberFormat( "0.00000 "); //用于Number的格式
WritableCellFormat priceFormat = new WritableCellFormat (detFont, nf);
DateFormat df=new DateFormat( "yyyy-MM-dd ");//用于日期的
WritableCellFormat dateFormat = new WritableCellFormat (detFont, df);
//剩下的事情,就是用上面的内容和格式创建一些单元格,再加到sheet中
l=new Label(0, 0, "用于测试的Excel文件 ", headerFormat);
sheet.addCell(l);
//add Title
int column=0;
l=new Label(column++, 2, "标题 ", titleFormat);
sheet.addCell(l);
l=new Label(column++, 2, "日期 ", titleFormat);
sheet.addCell(l);
l=new Label(column++, 2, "货币 ", titleFormat);
sheet.addCell(l);
l=new Label(column++, 2, "价格 ", titleFormat);
sheet.addCell(l);
//add detail
int i=0;
column=0;
l=new Label(column++, i+3, "标题 "+i, detFormat);
sheet.addCell(l);
d=new DateTime(column++, i+3, new java.util.Date(), dateFormat);
sheet.addCell(d);
l=new Label(column++, i+3, "CNY ", detFormat);
sheet.addCell(l);
n=new jxl.write.Number(column++, i+3, 5.678, priceFormat);
sheet.addCell(n);
i++;
column=0;
l=new Label(column++, i+3, "标题 "+i, detFormat);
sheet.addCell(l);
d=new DateTime(column++, i+3, new java.util.Date(), dateFormat);
sheet.addCell(d);
l=new Label(column++, i+3, "SGD ", detFormat);
sheet.addCell(l);
n=new jxl.write.Number(column++, i+3, 98832, priceFormat);
sheet.addCell(n);
//设置列的宽度
column=0;
sheet.setColumnView(column++, 20);
sheet.setColumnView(column++, 20);
sheet.setColumnView(column++, 10);
sheet.setColumnView(column++, 20);
workbook.write();
workbook.close();
‘玖’ java项目中怎么实现jsp页面Excel模板下载并弹框。
controller层关键代码:
@RequestMapping(value="/excel")
publicModelAndViewexportExcel()throwsException{
ModelAndViewmv=newModelAndView();
PageDatapd=newPageData();
pd=this.getPageData();
Map<String,Object>dataMap=newHashMap<String,Object>();
List<String>titles=newArrayList<String>();
titles.add("办事处");//1
titles.add("当日新增扫码商户(个)");//2
titles.add("当日交易笔数(笔)");//3
titles.add("当日交易金额");//4
titles.add("当日收益");//5
titles.add("累计新增扫码商户(个)");//6
titles.add("累计交易笔数(笔)");//7
titles.add("累计交易金额");//8
titles.add("累计收益");//9
dataMap.put("titles",titles);
Pagepage=newPage();
page.setPd(pd);
List<PageData>varOList=agencyService.list(page);
List<PageData>varList=newArrayList<PageData>();
for(inti=0;i<varOList.size();i++){
PageDatavpd=newPageData();
vpd.put("var1",varOList.get(i).get("AGENCYNAME").toString());//1
vpd.put("var2",varOList.get(i).get("TODAYINSTALL").toString());//2
vpd.put("var3",varOList.get(i).get("TODAYTRANS").toString());//3
vpd.put("var4",varOList.get(i).get("TODAYPRICE").toString());//4
vpd.put("var5",varOList.get(i).get("TODAYPAYMENT").toString());//5
vpd.put("var6",varOList.get(i).get("TOTALINSTALL").toString());//6
vpd.put("var7",varOList.get(i).get("TOTALTRANS").toString());//7
vpd.put("var8",varOList.get(i).get("TOTALPRICE").toString());//8
vpd.put("var9",varOList.get(i).get("TOTALPAYMENT").toString());//9
varList.add(vpd);
}
dataMap.put("varList",varList);
ObjectExcelViewerv=newObjectExcelView();
mv=newModelAndView(erv,dataMap);
returnmv;
}
POI生成EXCEL关键代码:
{
@SuppressWarnings("deprecation")
@Override
(Map<String,Object>model,
HSSFWorkbookworkbook,HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
//TODOAuto-generatedmethodstub
Datedate=newDate();
Stringfilename=Tools.date2Str(date,"yyyyMMddHHmmss");
HSSFSheetsheet;
HSSFCellcell;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+filename+".xls");
sheet=workbook.createSheet("sheet1");
List<String>titles=(List<String>)model.get("titles");
intlen=titles.size();
HSSFCellStyleheaderStyle=workbook.createCellStyle();//标题样式
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFontheaderFont=workbook.createFont(); //标题字体
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short)11);
headerStyle.setFont(headerFont);
shortwidth=20,height=25*20;
sheet.setDefaultColumnWidth(width);
for(inti=0;i<len;i++){//设置标题
Stringtitle=titles.get(i);
cell=getCell(sheet,0,i);
cell.setCellStyle(headerStyle);
setText(cell,title);
}
sheet.getRow(0).setHeight(height);
HSSFCellStylecontentStyle=workbook.createCellStyle();//内容样式
contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
List<PageData>varList=(List<PageData>)model.get("varList");
intvarCount=varList.size();
for(inti=0;i<varCount;i++){
PageDatavpd=varList.get(i);
for(intj=0;j<len;j++){
Stringvarstr=vpd.getString("var"+(j+1))!=null?vpd.getString("var"+(j+1)):"";
cell=getCell(sheet,i+1,j);
cell.setCellStyle(contentStyle);
setText(cell,varstr);
}
}
}
}
‘拾’ java操作excel,将多个excel模板写入到一个excel的多个sheet中
用poi
Workbook myWorkbook= new HSSFWorkbook(new FileInputStream("路径"));
Workbook workbookModel = new HSSFWorkbook(new FileInputStream("路径"));
for(int i= 0; i<workbookModel.getNumberOfSheets(); i++) {
HSSFSheet(myWorkbook, workbookModel.getSheet(i));
}