使用JCom动态生成Excel文件,并向其中填入数据

package org.zlong.jcom; import java.io.File; import java.sql.Date; import jp.ne.so_net.ga2.no_ji.jcom.ReleaseManager; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelApplication; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelRange; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbook; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbooks; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheet; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheets; /** * 动态生成Excel文件 并向其中填入数据 * @description * @version 1.0 * @author zhangl * @update 2011-4-8 上午10:15:33 */ public class TestExcel { public static void main(String[] args) { ReleaseManager rm = new ReleaseManager(); try { System.out.println("EXCEL startup..."); // if already started, open new window ExcelApplication excel = new ExcelApplication(rm); excel.Visible(true); // display any information System.out.println("Version=" + excel.Version()); System.out.println("UserName=" + excel.UserName()); System.out.println("Caption=" + excel.Caption()); System.out.println("Value=" + excel.Value()); ExcelWorkbooks xlBooks = excel.Workbooks(); ExcelWorkbook xlBook = xlBooks.Add(); // create new book // enumurate all files System.out.println("set infomation of files in current directory to cell ..."); ExcelWorksheets xlSheets = xlBook.Worksheets(); ExcelWorksheet xlSheet = xlSheets.Item(1); ExcelRange xlRange = xlSheet.Cells(); xlRange.Item(1, 1).Value("filename"); xlRange.Item(2, 1).Value("size"); xlRange.Item(3, 1).Value("last modified time"); xlRange.Item(4, 1).Value("is directory"); xlRange.Item(5, 1).Value("is file"); xlRange.Item(6, 1).Value("can read"); xlRange.Item(7, 1).Value("can write"); File path = new File("./"); //该目录下的所有文件(夹) String[] filenames = path.list(); for (int i = 0; i < filenames.length; i++) { File file = new File(filenames[i]); System.out.println(file); xlRange.Item(1, i + 2).Value(file.getName()); // filename(no // path) xlRange.Item(2, i + 2).Value((int) file.length()); // filesize xlRange.Item(3, i + 2).Value(new Date(file.lastModified())); // last// modified// time xlRange.Item(4, i + 2).Value(file.isDirectory() ? "Yes" : "No"); // directory// ? xlRange.Item(5, i + 2).Value(file.isFile() ? "Yes" : "No"); // file// ? xlRange.Item(6, i + 2).Value(file.canRead() ? "Yes" : "No"); // can// read// ? xlRange.Item(7, i + 2).Value(file.canWrite() ? "Yes" : "No"); // can// write// ? } String expression = "=Sum(B2:B" + (filenames.length + 1) + ")"; System.out.println("embed equation, calculate sum of filesize: " + expression); xlRange.Item(1, filenames.length + 2).Value("sum"); xlRange.Item(2, filenames.length + 2).Formula(expression); xlRange.Columns().AutoFit(); // fit columns // xlBook.Close(false, null, false); //关闭 // excel.Quit(); System.out.println("thank you ."); } catch (Exception e) { e.printStackTrace(); } finally { rm.release(); } } }

你可能感兴趣的:(使用JCom动态生成Excel文件,并向其中填入数据)