Java- Ecxel 文档操作

本文详细介绍如何使用Java POI库进行Excel文件的格式设置,包括单元格样式、边框、字体、对齐方式、高度宽度调整、自动换行、单元格合并等,并提供了实例代码。

原博: https://www.cnblogs.com/interdrp/p/4019583.html
存一下.
笨方法 ¬︿¬
Workbook:

	/**
	 * 判断是否文件格式,生成工作薄
	 */
File excel = new File(excelPath);
		Workbook wb = null;
		if (excel.isFile() && excel.exists()) {
			String[] split = excel.getName().split("\\."); // .是特殊字符,需要转义!!!!!
			// 根据文件后缀(xls/xlsx)进行判断
			FileInputStream fis = new FileInputStream(excel); // 文件流对象
			if (excel.toString().endsWith("xls")) {
				wb = new HSSFWorkbook(fis);
			} else if (excel.toString().endsWith("xlsx")) {

				wb = new XSSFWorkbook(fis);
			} else {
				throw new IOException("文件类型错误!");
			}

		}

(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)


格式问题:
原博: https://blog.youkuaiyun.com/z1074907546/article/details/50544178

依旧先是 ¬︿¬|||

				CellStyle createCellStyle = wb.createCellStyle(); //创建样式
				
				createCellStyle .setBorderBottom(CellStyle.BORDER_THIN ); //细线条   单元格下
				
		       createCellStyle .setBorderLeft(CellStyle.BORDER_THIN);  //细线条   单元格左
		       
		       createCellStyle .setBorderRight(CellStyle.BORDER_THIN );  //细线条   单元格右
		       
		       createCellStyle .setBorderTop(CellStyle.BORDER_THIN);  //细线条   单元格上
		       
			    createCellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); //设置前景色
			    
				createCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); //前景色设置必要条件
				
			    cell = row.createCell((short) 0); //创建单元格
			    
			    cell.setCellValue("aaa"); //为单元格赋值

颜色对照表:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)


原博: https://www.cnblogs.com/exmyth/p/5383545.html

package my.excel;   
  
import java.io.FileOutputStream;   
  
import org.apache.poi.ss.usermodel.Cell;   
import org.apache.poi.ss.usermodel.CellStyle;   
import org.apache.poi.ss.usermodel.Font;   
import org.apache.poi.ss.usermodel.Row;   
import org.apache.poi.ss.usermodel.Sheet;   
import org.apache.poi.ss.usermodel.Workbook;   
import org.apache.poi.ss.util.CellRangeAddress;   
import org.apache.poi.xssf.usermodel.XSSFCellStyle;   
import org.apache.poi.xssf.usermodel.XSSFColor;   
import org.apache.poi.xssf.usermodel.XSSFWorkbook;   
  
 
public class CellFormatExcel {   
       
    public static void main(String[] args) {   
        try {   
            // 创建Excel表格工作簿   
            Workbook wb = new XSSFWorkbook();   
            Sheet sheet = wb.createSheet("表格单元格格式化");   
               
            //============================   
            //       设置单元格的字体   
            //============================   
            Row ztRow = sheet.createRow((short)0);   
            Cell ztCell = ztRow.createCell(0);   
            ztCell.setCellValue("中国");   
            // 创建单元格样式对象   
            XSSFCellStyle ztStyle = (XSSFCellStyle) wb.createCellStyle();   
            // 创建字体对象   
            Font ztFont = wb.createFont();   
            ztFont.setItalic(true);                     // 设置字体为斜体字   
            ztFont.setColor(Font.COLOR_RED);            // 将字体设置为“红色”   
            ztFont.setFontHeightInPoints((short)22);    // 将字体大小设置为18px   
            ztFont.setFontName("华文行楷");             // 将“华文行楷”字体应用到当前单元格上   
            ztFont.setUnderline(Font.U_DOUBLE);         // 添加(Font.U_SINGLE单条下划线/Font.U_DOUBLE双条下划线)   
//          ztFont.setStrikeout(true);                  // 是否添加删除线   
            ztStyle.setFont(ztFont);                    // 将字体应用到样式上面   
            ztCell.setCellStyle(ztStyle);               // 样式应用到该单元格上   
               
            //============================   
            //        设置单元格边框   
            //============================   
            Row borderRow = sheet.createRow(2);   
            Cell borderCell = borderRow.createCell(1);   
            borderCell.setCellValue("中国");   
            // 创建单元格样式对象   
            XSSFCellStyle borderStyle = (XSSFCellStyle)wb.createCellStyle();   
            // 设置单元格边框样式   
            // CellStyle.BORDER_DOUBLE      双边线   
            // CellStyle.BORDER_THIN        细边线   
            // CellStyle.BORDER_MEDIUM      中等边线   
            // CellStyle.BORDER_DASHED      虚线边线   
            // CellStyle.BORDER_HAIR        小圆点虚线边线   
            // CellStyle.BORDER_THICK       粗边线   
            borderStyle.setBorderBottom(CellStyle.BORDER_THICK);   
            borderStyle.setBorderTop(CellStyle.BORDER_DASHED);   
            borderStyle.setBorderLeft(CellStyle.BORDER_DOUBLE);   
            borderStyle.setBorderRight(CellStyle.BORDER_THIN);   
               
            // 设置单元格边框颜色   
            borderStyle.setBottomBorderColor(new XSSFColor(java.awt.Color.RED));   
            borderStyle.setTopBorderColor(new XSSFColor(java.awt.Color.GREEN));   
            borderStyle.setLeftBorderColor(new XSSFColor(java.awt.Color.BLUE));   
               
            borderCell.setCellStyle(borderStyle);   
               
            //============================   
            //      设置单元内容的对齐方式   
            //============================   
            Row alignRow = sheet.createRow(4);   
            Cell alignCell = alignRow.createCell(1);   
            alignCell.setCellValue("中国");   
               
            // 创建单元格样式对象   
            XSSFCellStyle alignStyle = (XSSFCellStyle)wb.createCellStyle();   
               
            // 设置单元格内容水平对其方式   
            // XSSFCellStyle.ALIGN_CENTER       居中对齐   
            // XSSFCellStyle.ALIGN_LEFT         左对齐   
            // XSSFCellStyle.ALIGN_RIGHT        右对齐   
            alignStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);   
               
            // 设置单元格内容垂直对其方式   
            // XSSFCellStyle.VERTICAL_TOP       上对齐   
            // XSSFCellStyle.VERTICAL_CENTER    中对齐   
            // XSSFCellStyle.VERTICAL_BOTTOM    下对齐   
            alignStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);   
               
            alignCell.setCellStyle(alignStyle);   
               
            //============================   
            //      设置单元格的高度和宽度   
            //============================   
            Row sizeRow = sheet.createRow(6);   
            sizeRow.setHeightInPoints(30);                  // 设置行的高度   
               
            Cell sizeCell = sizeRow.createCell(1);     
            String sizeCellValue = "《Java编程思想》";            // 字符串的长度为10,表示该字符串中有10个字符,忽略中英文   
            sizeCell.setCellValue(sizeCellValue);       
            // 设置单元格的长度为sizeCellVlue的长度。而sheet.setColumnWidth使用sizeCellVlue的字节数   
            // sizeCellValue.getBytes().length == 16   
            sheet.setColumnWidth(1, (sizeCellValue.getBytes().length) * 256 );   
               
            //============================   
            //      设置单元格自动换行   
            //============================   
            Row wrapRow = sheet.createRow(8);   
            Cell wrapCell = wrapRow.createCell(2);   
            wrapCell.setCellValue("宝剑锋从磨砺出,梅花香自苦寒来");   
               
            // 创建单元格样式对象   
            XSSFCellStyle wrapStyle = (XSSFCellStyle)wb.createCellStyle();   
            wrapStyle.setWrapText(true);                    // 设置单元格内容是否自动换行   
            wrapCell.setCellStyle(wrapStyle);   
               
            //============================   
            //         合并单元格列   
            //============================   
            Row regionRow = sheet.createRow(12);   
            Cell regionCell = regionRow.createCell(0);   
            regionCell.setCellValue("宝剑锋从磨砺出,梅花香自苦寒来");   
               
            // 合并第十三行中的A、B、C三列   
            CellRangeAddress region = new CellRangeAddress(12, 12, 0, 2); // 参数都是从O开始   
            sheet.addMergedRegion(region);   
               
            //============================   
            //         合并单元格行和列   
            //============================   
            Row regionRow2 = sheet.createRow(13);   
            Cell regionCell2 = regionRow2.createCell(3);   
            String region2Value = "宝剑锋从磨砺出,梅花香自苦寒来。"  
                                + "采得百花成蜜后,为谁辛苦为谁甜。"  
                                + "操千曲而后晓声,观千剑而后识器。"  
                                + "察己则可以知人,察今则可以知古。";   
            regionCell2.setCellValue(region2Value);   
               
            // 合并第十三行中的A、B、C三列   
            CellRangeAddress region2 = new CellRangeAddress(13, 17, 3, 7); // 参数都是从O开始   
            sheet.addMergedRegion(region2);   
               
            XSSFCellStyle region2Style = (XSSFCellStyle)wb.createCellStyle();   
            region2Style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);   
            region2Style.setWrapText(true);                     // 设置单元格内容是否自动换行   
            regionCell2.setCellStyle(region2Style);   
                           
            //============================   
            // 将Excel文件写入到磁盘上   
            //============================   
            FileOutputStream is = new FileOutputStream("document/CellFormatExcel.xlsx");   
            wb.write(is);   
            is.close();   
               
            System.out.println("写入成功,运行结束!");   
        } catch(Exception e) {   
            e.printStackTrace();   
        }   
    }   
} 

(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)(●’◡’●)


合并:
原博: https://www.cnblogs.com/yanjie-java/p/8329276.html


前端:

window.open("data/export");

后台实现:

 public void exportFileList(HttpServletResponse response, HSSFWorkbook wb, String name)  {
        /*  直接浏览器*/
        String downloadFileName;
        OutputStream out ;
        try {
            downloadFileName = new String(name.getBytes("UTF-8"),"iso-8859-1");
            String headStr ="attachment; filename=\"" + downloadFileName +"\"";
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            wb.write(out);
            out.flush();
            wb.close();
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  }
/* 本地 */
 FileOutputStream output;
        try {
            output = new FileOutputStream("d:\\workbook.xls");
            wb.write(output);
            output.flush();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
   /**
     *设置单元格边框,线条颜色 
     **/
    public HSSFCell setCellStyle(HSSFWorkbook wb,HSSFCell cell) {
        // 设置单元格边框   
      CellStyle style = wb.createCellStyle();
      
       //边框-实线  
      style.setBorderBottom(BorderStyle.MEDIUM);
      style.setBorderLeft(BorderStyle.MEDIUM);
      style.setBorderRight(BorderStyle.MEDIUM);
      style.setBorderTop(BorderStyle.MEDIUM);

       //颜色 黑色 
      style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
      style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
      style.setRightBorderColor(IndexedColors.BLACK.getIndex());
      style.setTopBorderColor(IndexedColors.BLACK.getIndex());
      HSSFFont font = wb.createFont();
      font.setBold(true); //字体加粗/true
      cell.setCellStyle(style);
      return cell;
      
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值