需要帮助在java中用超链接字段文件编写excel

时间:2012-11-05 11:03:45

标签: java excel xls xlsx

我正在尝试通过具有超链接字段的java编写excel文件。

我是从对象列表中写的。请检查我的代码。

当我给对象列表时,它正在工作。它正在编写xls文件。

但我也想在其中写下超链接。我应该在下面的代码中做些什么改变。?

刚开始使用exportToExcel方法。

package com.ksh;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ksh.Final.Link;

public class OwnClass {

    private static SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static Map<Class<?>, Class<?>> javaBasicObjectTypeMap = new HashMap();
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static Map<Class<?>, Class<?>> floatingPointTypeMap = new HashMap();

    static 
    {
        javaBasicObjectTypeMap.put(Integer.class, Integer.class);
        javaBasicObjectTypeMap.put(Long.class, Long.class);
        javaBasicObjectTypeMap.put(Float.class, Float.class);
        javaBasicObjectTypeMap.put(Double.class, Double.class);
        javaBasicObjectTypeMap.put(BigDecimal.class, BigDecimal.class);
        javaBasicObjectTypeMap.put(Character.class, Character.class);
        javaBasicObjectTypeMap.put(String.class, String.class);
        javaBasicObjectTypeMap.put(Date.class, Date.class);

        floatingPointTypeMap.put(Float.class, Float.class);
        floatingPointTypeMap.put(Double.class, Double.class);
        floatingPointTypeMap.put(BigDecimal.class, BigDecimal.class);
    }

    @SuppressWarnings("rawtypes")
    public static String exportToExcel(List<?> objectList, 
                                       ExcelFileParameter config, 
                                       Map<String, String> fieldNameTitleMap)throws Exception
    {
        String filePath = config.getExcelFileAbsolutePath();
        if (filePath.isEmpty()) 
        {
            filePath = dateTimeFormatter.format(new Date()) + ".xlsx";
        }
        File excelFile = new File(filePath);
        FileOutputStream fos = null;
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet();
        List rowlist = convertObjectToRowList(objectList, config, fieldNameTitleMap);

        System.out.println("Kshitij : "+rowlist.size()+"Type : ===="+rowlist.get(0).getClass().getName());

        for (int i = 0; (rowlist != null) && (i < rowlist.size()); i++) 
        {
            List row = (List)rowlist.get(i);
            XSSFRow excelRow = sheet.createRow(i);
            for (int j = 0; (row != null) && (j < row.size()); j++) 
            {
                XSSFCell cell = excelRow.createCell(j);
                cell.setCellValue((String)row.get(j));
            }
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workBook.write(bos);
        try
        {
            fos = new FileOutputStream(excelFile);
            fos.write(bos.toByteArray());
        } 
        catch (Exception ex) 
        {
            throw ex;
        } 
        finally 
        {
            fos.flush();
            fos.close();
        }

        return excelFile.getAbsolutePath();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static List<List<String>> convertObjectToRowList(List<?> objectList, 
                                                             ExcelFileParameter config, 
                                                             Map<String, String> fieldNameTitleMap) throws Exception

    {
        if (objectList == null) 
        {
            throw new Exception("objectList is null!");
        }
        if (objectList.size() == 0) 
        {
            throw new Exception("objectList is empty!");
        }

        List rowList = new ArrayList();
        Class itemClass = objectList.get(0).getClass();
        System.out.println("Object List Type is : "+itemClass.getName());

        if (javaBasicObjectTypeMap.containsKey(itemClass))
        {
              System.out.println("Non Primitive Type From Java Library");
              for (Iterator localIterator = objectList.iterator(); localIterator.hasNext(); ) 
              { 
                  Object obj = localIterator.next();
                  String value = convertFieldValueToString(itemClass, obj, config);
                  List row = new ArrayList();
                  row.add(value);
                  rowList.add(row);
              }
        }
        else
        {
              System.out.println("User Defined Class Type just got");
              List allFields = getFields(itemClass);
              Object excelFields = new ArrayList();
              List header = new ArrayList();
              String fieldName = null;

              for (int i = 0; (allFields != null) && (i < allFields.size()); i++) 
              {
                    fieldName = ((Field)allFields.get(i)).getName();
                    if ((fieldNameTitleMap != null) && (fieldNameTitleMap.keySet().size() > 0)) 
                    {
                        if (fieldNameTitleMap.containsKey(fieldName)) 
                        {
                            ((List)excelFields).add((Field)allFields.get(i));
                            header.add((String)fieldNameTitleMap.get(fieldName));
                        }
                    } 
                    else 
                    {
                        ((List)excelFields).add((Field)allFields.get(i));
                        header.add(fieldName);
                    }
              }
              rowList.add(header);
              for(Object object : objectList)
              {
                  List row = convertToRow(object, config, (List)excelFields);
                  rowList.add(row);
              }
        }
        return rowList;
      }

      private static String convertFieldValueToString(Class<?> fieldType, 
                                                      Object fieldValue, 
                                                      ExcelFileParameter config) throws Exception 
      {

            if (fieldValue == null) 
            {
                return config.getNullValueStrig();
            }
            if (fieldType.isAssignableFrom(Date.class)) 
            {
                SimpleDateFormat dateTimeFormat = config.getDateTimeFormat();
                if (dateTimeFormat == null) 
                {
                    return fieldValue.toString();
                }
                dateTimeFormat.format(fieldValue);
            }

            if ((fieldType == Float.TYPE)  || 
                (fieldType == Double.TYPE) || 
                (floatingPointTypeMap.containsKey(fieldType)))
            {
                  DecimalFormat decimalFormat = config.getDecimalFormat();
                  if (decimalFormat == null) 
                  {
                    return fieldValue.toString();
                  }
                  decimalFormat.format(fieldValue);
            }

            System.out.println("99999999999999999999999999999999999999999 : "+fieldType);
            if(fieldType == Link.class)
            {
                System.out.println("Link Value is Found...");
                System.out.println("Field Value : "+fieldValue.toString());
            }

            return fieldValue.toString();
      }

      @SuppressWarnings({ "rawtypes", "unchecked" })
      private static List<Field> getFields(Class<?> clazz)
      {
            List list = new ArrayList();
            Field[] fieldlist = clazz.getDeclaredFields();
            for (int i = 0; (fieldlist != null) && (i < fieldlist.length); i++)
            {
                Field field = fieldlist[i];
                Class type = fieldlist[i].getType();
                System.out.println("Type :" +type);
                int mod = fieldlist[i].getModifiers();
                System.out.println("Mode :" +mod);
                if ((!Modifier.isFinal(mod)) && (!Modifier.isStatic(mod))) 
                {
                    if (type.isPrimitive())
                    {
                        list.add(field);
                    }
                    else if (javaBasicObjectTypeMap.containsKey(type)) 
                    {
                        list.add(field);
                    }
                }
            }
            for(Object object : list)
            {
                Field field = (Field) object;
                System.out.println(field.getName());
            }
            return list;

      }

      @SuppressWarnings({ "rawtypes", "unchecked" })
      private static List<String> convertToRow( Object object, 
                                                ExcelFileParameter config, 
                                                List<Field> fieldList )
      {

          List row = new ArrayList();
          for (int i = 0; (fieldList != null) && (i < fieldList.size()); i++) 
          {
              try 
              {
                  Field field = (Field)fieldList.get(i);
                  field.setAccessible(true);
                  Class fieldType = field.getType();
                  Object fieldValue = field.get(object);
//                System.out.println("Field Type : "+fieldType +"FieldValue : "+fieldValue);
                  String value = convertFieldValueToString(fieldType, fieldValue, config);
                  System.out.println("--------------------------------------------------"+value);
                  row.add(value);

              } 
              catch (Exception ex) 
              {
                  row.add("ERROR:" + ex.toString());
              }
          }
          System.out.println("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"+row.size());
        return row;
      }


}

意味着将对象链接写入excel文件。它正在工作,但需要编写超链接字段。

2 个答案:

答案 0 :(得分:0)

我认为此代码示例可以为您提供帮助。

if(row.get(j) instanceof Link){
     Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
     link.setAddress("http://poi.apache.org/");
     cell.setHyperlink(link);
 }else{
     Your code..
 }

将String类更改为Object类以避免错误。

参考链接:

http://www.docjar.com/html/api/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java.html

答案 1 :(得分:0)

基本上这段代码会在Cell中生成HyperLink:

Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("AHyperLink");
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("Google");
Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
link.setAddress("http://www.google.com/");
cell.setHyperlink(link);

在代码中使用一种简单的方法是将URL模式与在以下位置获得的字段值相匹配:

XSSFCell cell = excelRow.createCell(j);
cell.setCellValue((String)row.get(j)); //  match the result of row.get(j)

如果是URL,请使用上面的代码添加HyperLink,如果不是仅使用您的代码

*编辑:

使用Link对象识别链接可能会更好,您必须以当时可以使用LinkString的方式重写代码细胞创造。