1

我正在尝试通过具有超链接字段的 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文件。它正在工作,但需要编写超链接字段。

4

2 回答 2

0

基本上这段代码将在单元格中生成一个超链接:

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,请使用上面的代码添加超链接,如果不只是使用您的代码

*编辑:

使用您的 Object 来识别链接可能会更好Link,您必须以您可以使用的方式LinkString在创建 Cell 时重写代码。

于 2012-11-05T11:39:14.817 回答
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

于 2012-11-05T11:27:56.523 回答