Location>code7788 >text

Java to create an Excel tool class

Popularity:945 ℃/2025-04-17 18:32:25

An Excel file is essentially a zip compressed file. You can decompress it to obtain sub-files. On the contrary, you can get Excel files by modifying the suffix name after compressing the subfile.


XLSX files are mainly composed of the following parts:
[Content_Types].xml‌: Describes the types and relationships of all components in the XLSX file. (Core file)
_rels/.rels‌: Contains the relationship information between all components in the workbook. (Core file)
docProps/‌: Contains the attribute information of the document.
xl/‌: Contains metadata of the entire workbook, such as worksheet name, style, etc. (Core file)
xl/_rels/‌: Contains the relationship information between all worksheets in the workbook. (Core file)
xl/worksheets/‌: Contains XML files for each worksheet in the workbook, such as, etc. (Core file)
xl/‌: Store shared string data.
xl/‌: Store cell style information.
xl/‌media/‌: Contains embedded media files, such as GIF, JPG, etc.
xl/drawings/‌: Media file relationship information, media file size and location information, etc.
xl/theme/‌: Office theme xml file

If there are no related core files, an error will occur when opening the file.

 

If you want to encapsulate Excel tool classes yourself, you must understand ZipInputStream and ZipOutputStream.

ZipInputStream parses XLSX files:

package test;

 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;

 import ;
 import ;

 import org.;
 import org.;

 public class Main {
	 public static void main(String[] args) throws IOException {
		 Main main = new Main("C:/Users/June/Desktop/");
		 ();
     }
	
	 ZipInputStream zis;
	 public Main(String pathname) throws FileNotFoundException {
		 zis = new ZipInputStream(new FileInputStream(new File(pathname)));
	 }
	
	 public void readDocuments() throws IOException {
		 try {
			 ZipEntry zipEntry;
			 while((zipEntry = ())!=null){
				 String entryName = ();//Each ZipEntry is a file
				 if(("xl/media")){
					 readMedia(entryName);
				 }else{
					 readDocument(entryName);
				 }
			 }
		 } finally {
			 if(zis!=null){
				 ();
			 }
		 }
	 }
	
	 //Process XML files
	 private void readDocument(String entryName) {
		 Element root = parse(zis);//XML file root element
		 //Processing logic
		
	 }
	 //Processing media files
	 private void readMedia(String entryName) {
		
	 }
	
	 // 1. Create a DOM parser factory
     private static final DocumentBuilderFactory factory = ();
     static {
         try {
             // Disable external entities (security protection)
             ("/xml/features/disallow-doctype-decl", true);
             ("/sax/features/external-general-entities", false);
             ("/sax/features/external-parameter-entities", false);
         } catch (Exception ignored) {

         }
     }
     private static Element parse(InputStream is) {
         try {
             // 2. Create a DOM parser
             DocumentBuilder builder = ();
             // 3. Parsing XML files
             Document doc = (is);
             // 4. Standardized document structure
             ().normalize();
             // 5. Get the root element
             return ();
         } catch (Exception ignored) {

         }
         return null;
     }
    
 }

 

ZipOutputStream outputs XLSX file:

The write output method is to output byte[], and you can use String's getBytes() method. Just output the string of the xml structure into a byte array

package test;

 import ;
 import ;
 import ;
 import ;
 import ;

 public class Main {
	 public static void main(String[] args) throws IOException {
		 Main main = new Main("C:/Users/June/Desktop/");
		 ();
     }
	
	 ZipOutputStream zos;
	 public Main(String pathname) throws IOException {
		 File f = new File(pathname);
		 if(!().exists()){
			 ().mkdirs();
		 }
		 if(!()){
			 ();
		 }
		 zos = new ZipOutputStream(new FileOutputStream(f));
	 }
	
	 public void write() throws IOException {
		 try {
			 (new ZipEntry("_rels/.rels"));
			 //Output.rels file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 (new ZipEntry("xl/"));
			 //Output file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 (new ZipEntry("xl/"));
			 //Output file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 (new ZipEntry("xl/_rels/"));
			 //Output file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 (new ZipEntry("xl/"));
			 //Output file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 (new ZipEntry("xl/worksheets/"));
			 //Output file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 (new ZipEntry("[Content_Types].xml"));
			 //Output [Content_Types].xml file structure
			 ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>".getBytes());
			 //.....
			
			 ();
		 } finally {
			 if(zos != null){
				 ();
				 ();
			 }
		 }
	 }
    
 }

 

The following is an Excel tool class and test code that I encapsulated myself.

package test;

 import ;
 import ;
 import ;
 import ;
 import ;
 import ;

 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;
 import ;


 public class ExcelTest {

	 public static void main(String[] args) throws IOException {
		 File f = new File("C:/Users/June/Desktop/");
		 if(!()) ();
		 OutputStream os = (());
		 ExcelWriter excel = (os);
		 Worksheet sheet1 = (null);

		 Cols cols = ();
		 (1,3,27.0);// Columns 1 to 3 are all 27.0
		
		 MergeCells mergeCells = ();
		 ("B", 4, "C", 5);//Merge B4-C5
		
		 SheetFormatPr sheetFormatPr = ();
		 (9);//Default all column widths
		 (90);//Default all row heights

		 SheetData sheet1Data = ();
		 (0, 0, "111");//The value of the first row and the first column is 111
		 (0, 72.0);//The first line height is 72.0
		
		 List<List<String>> dataList = new ArrayList<List<String>>();
		 List<String> r2 = new ArrayList<String>();
		 ("A2");
		 ("B2");
		 ("C2");
		 ("D2");
		 (r2);
		 List<String> r3 = new ArrayList<String>();
		 ("A3");
		 ("B3");
		 ("C3");
		 (r3);
 // ("A", 2, dataList);//Assign from A2
		 ("A2", dataList);//Select value starting from A2
		
		 ExcelStyle cs = new ExcelStyle();
		 Font font = new Font();
		 (true);//Font bold
		 (13);//Font size
		 (true);//Font italic
		 ("Bold");//Font Name
		 ("ed6e19");//Font color
		 (font);//Font style
		 Fill fill = new Fill();//Fill
		 ();
		 ("30c7c9");//Background color
		 ("30c7c9");//Foreground color
		 (fill);//Fill color
		 Border border = new Border();
		 ("000000", );//Black solid line
		 (border);//Border
		 Alignment alignment = new Alignment();
		 ();//Center the center
		 ();//Center vertically
		 (true);//Automatic wrapping
		 (alignment);
		 (1, 0, cs);
		 (1, 1, cs);
		
		 ();
	 }
	
 }

Source code:/files/blogs/824473/?t=1744885655&download=true

jar package:/files/blogs/824473/?t=1744885560&download=true