2011-06-28 150 views

回答

23

我建議你使用Apache POI framework(特別是HSSF/XSSF API)寫出來的XLS文件。

對於讀取CSV文件,我建議您使用OpenCSV,因爲它會照顧您的轉義字符等。

here放在一起的POI例子,從here的OpenCSV例子給你:

import java.io.*; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.ss.usermodel.*; 
import au.com.bytecode.opencsv.CSVReader; 

class Test { 
    public static void main(String[] args) throws IOException { 
     Workbook wb = new HSSFWorkbook(); 
     CreationHelper helper = wb.getCreationHelper(); 
     Sheet sheet = wb.createSheet("new sheet"); 

     CSVReader reader = new CSVReader(new FileReader("data.csv")); 
     String[] line; 
     int r = 0; 
     while ((line = reader.readNext()) != null) { 
      Row row = sheet.createRow((short) r++); 

      for (int i = 0; i < line.length; i++) 
       row.createCell(i) 
        .setCellValue(helper.createRichTextString(line[i])); 
     } 

     // Write the output to a file 
     FileOutputStream fileOut = new FileOutputStream("workbook.xls"); 
     wb.write(fileOut); 
     fileOut.close(); 
    } 
} 

enter image description hereenter image description here

+0

這將是非常緩慢的方法,當你的CSV擁有超過10萬線 – whd

6

Apache POI是一個庫,可以處理各種微軟辦公文檔,包括MS Excel。您可以使用簡單的java代碼讀取csv文件的內容,並使用該庫創建並保存MS Excel文檔。

0

使用Groovy,我會做這種方式:

// groovy to generate large csv file 
def GROOVY_HOME = new File(System.getenv('GROOVY_HOME')) 
if (!GROOVY_HOME.canRead()) { 
    println("Missing environment variable GROOVY_HOME: '${GROOVY_HOME}'") 
    System.exit(0) 
} 

File file = new File("csv.csv") 
if (file.exists()) { 
    assert file.delete() 
    assert file.createNewFile() 
} 

boolean append = true 
FileWriter fileWriter = new FileWriter(file, append) 
BufferedWriter buffWriter = new BufferedWriter(fileWriter) 

buffWriter.write "sdiType=ReferenceValue,,,\n" 
buffWriter.write "ListName,ListStartDate,Value,ValueStartDate\n" 
println("Writing to file 'csv.csv'") 

def y = 5000 
while (y-- > 0) { 
    buffWriter.write "test" + y + ",1/1/2001,2008,1/1/2001\n" 
} 

buffWriter.flush() 
buffWriter.close()