SoFunction
Updated on 2025-05-19

Sample code for implementing Java export data to csv file

In many cases in the project, you will encounter the need to export data to the csv file. The code is as follows:

package ;
 
import ;
import .*;
import ;
import ;
 
public class CSVUtil {
    /**
      * Export csv file
      * @param response The settings required for exporting files are set in the response
      * @param head English comma separated data table header
      * @param dataList English comma separated data
      * @param filename Exported file name
      */
    public static void createCSVFile(HttpServletResponse response, List<String> head, List<String> dataList,
                                     String filename) {
        File csvFile = null;
        BufferedWriter csvWtriter = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            csvFile=new File(filename);
 
            // GB2312 enables the delimiter ","            FileOutputStream fileOutputStream=new FileOutputStream(csvFile);
            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
//            (new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
            csvWtriter = new BufferedWriter(outputStreamWriter);
 
            // Write to the header of the file            if (()>0){
                ((0));
                ();
            }
 
            // Write file contents            for (String item:dataList){
                (item);
                ();
            }
            ();
 
            in = new FileInputStream(csvFile);
            int len = 0;
            byte[] buffer = new byte[1024*1024*5];
            out = ();
 
            // Set this response to the file download response            ("application/csv;charset=UTF-8");
            ("Content-Disposition",
                    "attachment; filename=" + ((), "UTF-8"));
            ("UTF-8");
            // Write the UTF-8 file logo header first            (new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
            while ((len = (buffer)) > 0) {
                (buffer, 0, len);
            }
            ();
        } catch (Exception e) {
            ();
        } finally {
            try {
                if (in != null) {
                    ();
                }
                if (out != null) {
                    ();
                }
                if (csvFile != null) {
                    ();
                }
                if (csvWtriter != null) {
                    ();
                }
            } catch (IOException e) {
                ();
            }
        }
    }
 
    /**
      * Save to csv file, not export
      * @param fileName Saved filename
      * @param tempDir file save path
      * @param head English comma separated data table header
      * @param dataList English comma separated data
      */
    public static void SaveTxtFile(String fileName, String tempDir,List<String> head,List<String> dataList) {
        String filePath=tempDir+"/"+fileName;
        try{
            FileOutputStream fileOutputStream=new FileOutputStream(filePath);
            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
            (new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
            BufferedWriter writer=new BufferedWriter(outputStreamWriter);
            ((0));
            ();
            for (String item:dataList){
                (item));
                ();
            }
            ();
        }
        catch (IOException e){
            (());
        }
    }
}

Method supplement

Export csv format file

The essence of exporting csv format files is to export commas-separated text data

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

import ;  

import ;
   

   
/**
  * File operation
  */  
public class CSVUtils {  
    
    
    /**
     * Function description: Get the BOM signature at the beginning of the UTF-8 encoded text file.
     * BOM (Byte Order Mark) is a standard mark used in UTF encoding schemes to identify encoding.  Example: When the receiver receives a byte stream starting with EF BB BF, he knows it is UTF-8 encoding.
     * @return BOM signature at the beginning of UTF-8 encoded text file
     */
    public static String getBOM() {

         byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
         return new String(b);
    }
    
  /**
    * Generate CVS files
    * @param exportData
    * Source Data List
    * @param map
    * csv file list header map
    * @param outPutPath
    * File path
    * @param fileName
    * File name
    * @return
    */  
  @SuppressWarnings("rawtypes")  
  public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath,  
                   String fileName) {  
    File csvFile = null;  
    BufferedWriter csvFileOutputStream = null;  
    try {  
      File file = new File(outPutPath);  
      if (!()) {  
        ();  
      }  
      //Define the file name format and create      csvFile =new File(outPutPath+fileName+".csv");
      ();  
      // UTF-8 enables the delimiter ","      //If the production file is garbled, use gbk in Windows and use UTF-8 in Linux      csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(  
        csvFile), "UTF-8"), 1024);  
      
      //Write the first byte stream to prevent garbled code      (getBOM());
      // Write to the header of the file      for (Iterator propertyIterator = ().iterator(); ();) {  
         propertyEntry = () ();  
        ((String) () != null ? (String) () : "" );  
        if (()) {  
          (",");  
        }  
      }  
      ();  
      // Write file contents      for (Iterator iterator = (); ();) {  
          Object row = (Object) ();
        for (Iterator propertyIterator = ().iterator(); propertyIterator  
          .hasNext();) {  
           propertyEntry = () propertyIterator  
            .next();  
          String str=row!=null?((String)((Map)row).get( ())):"";
if((str)){
              str="";
          }else{
              str=("\"","\"\"");
              if((",")>=0){
                  str="\""+str+"\"";
              }
          }
          (str);  
          if (()) {  
            (",");  
          }  
        }  
        if (()) {  
          ();  
        }  
      }  
      ();  
    } catch (Exception e) {  
      ();  
    } finally {  
      try {  
        ();  
      } catch (IOException e) {  
        ();  
      }  
    }  
    return csvFile;  
  }  
   
  /**
    * Generate and download the csv file
    * @param response
    * @param exportData
    * @param map
    * @param outPutPath
    * @param fileName
    * @throws IOException
    */
  @SuppressWarnings("rawtypes")
  public static void exportDataFile(HttpServletResponse response,List exportData, LinkedHashMap map, String outPutPath,String fileName) throws IOException{
      File csvFile = null;  
        BufferedWriter csvFileOutputStream = null;  
        try {  
          File file = new File(outPutPath);  
          if (!()) {  
            ();  
          }  
          //Define the file name format and create          csvFile =new File(outPutPath+fileName+".csv");
          if(()){
             (); 
          }
          ();  
          // UTF-8 enables the delimiter ","          //If the production file is garbled, use gbk in Windows and use UTF-8 in Linux          csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024);  
          //Write the first byte stream to prevent garbled code          (getBOM());
          // Write to the header of the file          for (Iterator propertyIterator = ().iterator(); ();) {  
             propertyEntry = () ();  
            ((String) () != null ? (String) () : "" );  
            if (()) {  
              (",");  
            }  
          }  
          ();  
          // Write file contents          for (Iterator iterator = (); ();) {  
            Object row = (Object) ();  
            for (Iterator propertyIterator = ().iterator(); propertyIterator  
              .hasNext();) {  
               propertyEntry = () propertyIterator  
                .next();  
              String str=row!=null?((String)((Map)row).get( ())):"";
              if((str)){
                  str="";
              }else{
                  str=("\"","\"\"");
                  if((",")>=0){
                      str="\""+str+"\"";
                  }
              }
              (str);  
              if (()) {  
                (",");  
              }  
            }  
            if (()) {  
              ();  
            }  
          }  
          ();  
        } catch (Exception e) {  
          ();  
        } finally {  
          try {  
            ();  
          } catch (IOException e) {  
            ();  
          }  
        }  
        
        
       
       
        InputStream in = null;  
        try {  
          in = new FileInputStream(outPutPath+fileName+".csv");  
          int len = 0;  
          byte[] buffer = new byte[1024];  
         
          OutputStream out = (); 
          (); 
           
          ("application/csv;charset=UTF-8");  
          ("Content-Disposition","attachment; filename=" + (fileName+".csv", "UTF-8"));  
          ("UTF-8"); 
          while ((len = (buffer)) > 0) {  
            (new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });  
            (buffer, 0, len);  
          }
          ();
        } catch (FileNotFoundException e) {  
        } finally {  
          if (in != null) {  
            try {  
              ();  
            } catch (Exception e) {  
              throw new RuntimeException(e);  
            }  
          }  
        }
       
  }
  
  /**
    * Delete all files under filePath in this directory
    * @param filePath
    * File directory path
    */  
  public static void deleteFiles(String filePath) {  
    File file = new File(filePath);  
    if (()) {  
      File[] files = ();  
      for (int i = 0; i < ; i++) {  
        if (files[i].isFile()) {  
          files[i].delete();  
        }  
      }  
    }  
  }  
   
  /**
    * Delete a single file
    * @param filePath
    * File directory path
    * @param fileName
    * File name
    */  
  public static void deleteFile(String filePath, String fileName) {  
    File file = new File(filePath);  
    if (()) {  
      File[] files = ();  
      for (int i = 0; i < ; i++) {  
        if (files[i].isFile()) {  
          if (files[i].getName().equals(fileName)) {  
            files[i].delete();  
            return;  
          }  
        }  
      }  
    }  
  }  
   
  /**
    * Test data
    * @param args
    */  
  @SuppressWarnings({ "rawtypes", "unchecked" })  
  public static void main(String[] args) {  
    List exportData = new ArrayList<Map>();  
    Map row1 = new LinkedHashMap<String, String>();  
    ("1", "11");  
    ("2", "12");  
    ("3", "13");  
    ("4", "14");  
    (row1);  
    row1 = new LinkedHashMap<String, String>();  
    ("1", "21");  
    ("2", "22");  
    ("3", "23");  
    ("4", "24");  
    (row1);  
    LinkedHashMap map = new LinkedHashMap();  

    //Set the column name    ("1", "First Column Name");  
    ("2", "Second Column Name");  
    ("3", "Third Column Name");  
    ("4", "Fourth Column Name");  
    //This file is uploaded to the path and can be configured to read from the database in the database, which is more convenient!    String path = "E:/";  

   //File name = Production file name + timestamp    String fileName = "File Export";  
    File file = (exportData, map, path, fileName);  
    String fileName2 = ();  
    ("File Name:" + fileName2);  
  }  
}  

Implement Csv file import and export

Import

 	/**
	  * Read the crv file and convert it to List
	  *
	  * @param separator crv file separator
	  * @param file file to be read
	  * @return crv object list
	  */
	public static <T> List<T> read(String separator, File file, Class<T> clazz) {
		List<T> result = ();
		try {
			BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
			//Set the separator			CsvFormat csvFormat = new CsvFormat();
			(separator);

			CsvParserSettings parserSettings = new CsvParserSettings();
			(rowProcessor);
			(csvFormat);

			CsvParser parser = new CsvParser(parserSettings);
			InputStream in = (());
			(in);
			//Read line by line			result = ();
		} catch (Exception e) {
            ("Import csv file failed. message: ", e);
		}
		return result;
	}

test

	@Getter
	@Setter
	@NoArgsConstructor
	@AllArgsConstructor
	@ToString
	public static class User implements Serializable {
		@Parsed(filed = "name")
        private String name;
        @Parsed(filed = "age")
        private Integer age;
    }

	public static void main(String[] args) {

		File file = new File("E:\\");
		List<User> users = (",", file, );
		(::println);

	}

Export

Create a tool class to use, paste the import and export method in and use it

    /**
      * csv file export
      *
      * @param data Export data
      * @param file Export the destination file
      * @param separator splitter
      * @param clazz Export object
      * @param <T> Data object generics
      */
    public static &lt;T&gt; void export(Collection&lt;T&gt; data, File file, String separator, Class&lt;T&gt; clazz) {
        try {
            CsvWriterSettings settings = new CsvWriterSettings();
            //Set the separator            CsvFormat csvFormat = new CsvFormat();
            (separator);
            (csvFormat);
            (false);
            (new BeanWriterProcessor&lt;&gt;(clazz));
            CsvWriter writer = new CsvWriter((()), "utf-8", settings);
            // Write to the header            (());
            (writer::processRecord);
            ();
        } catch (Exception e) {
            ("export .csv file failed. message.", e);
        }
    }

test

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
	@ToString
    public static class User implements Serializable {
        @Parsed(filed = "name")
        private String name;
        @Parsed(filed = "age")
        private Integer age;
    }

    public static void main(String[] args) {
        User user1 = new User("Zhang San", 18);
        User user2 = new User("Li Si", 19);
        List&lt;User&gt; users = (user1, user2);
        File file = new File("E:\\");
        (users, file, ",", );
    }

This is the article about Java implementation of sample code for exporting data to csv files. For more related Java exporting data to csv content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!