Java Export CSV method implementation explanation _java

Source: Internet
Author: User
Tags object object stringbuffer

First, the SQL statement in the Ibatis is used to query for the records to be obtained and store them in the list:

Copy Code code as follows:

list<?> results = This.reportService.getArrayBeanReportDataSource (Super.getquery_sql_csv (), query_obj);

In this case, because we are going to write public methods, so use? Instead of using a certain type to label.

It is necessary to use the value of the property of the object retrieved from the list by reflection.

Copy Code code as follows:

string[] Column = Super.getreport_data_column (). Split (",");

This sentence gets the attributes that need to be achieved through spring's injection.

Copy Code code as follows:

StringBuffer sb = new StringBuffer ();
field[] fields = Query_obj.getclass (). Getdeclaredfields ();

Gets the property declared in the object by using the Getdeclaredfields () method.

Then, first compare the required attributes with all the properties, because the following operations are generated under the required attributes, and if there is no comparison, there are many empty columns in the exported CSV file, which is easy to understand.
Also, note that when declared as private, the declared property must use the Setaccessible () method to set its value to be removed.

Finally, it is OK to use the loop to separate the values of the columns with commas and write them to the file.

Copy Code code as follows:

for (Object object:results) {
try{
Field.setaccessible (fields, true);
for (int i=0;i<column.length;i++) {
for (int j=0;j<fields.length;j++) {
if (Fields[j].getname (). Equals (Column[i])) {
if (i!= (column.length-1)) {
Sb.append ((Fields[j].get (object) ==null? ": Fields[j].get (object)) +", ");
Break
}else{
Sb.append ((Fields[j].get (object) ==null? ": Fields[j].get (object) +" \ r \ n ");
Break
}
}
}
}
}catch (Exception e) {
E.printstacktrace ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.