首页 \ 问答 \ spring boot要怎么接收json对象

spring boot要怎么接收json对象

更新时间:2023-09-06 15:09

最新回答

代码实例:

package edu.sjtu.erplab.poi;

import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.inputstream;
import java.text.simpledateformat;
import java.util.date;
import java.util.hashmap;
import java.util.map;

import org.apache.poi.hssf.usermodel.hssfcell;
import org.apache.poi.hssf.usermodel.hssfdateutil;
import org.apache.poi.hssf.usermodel.hssfrow;
import org.apache.poi.hssf.usermodel.hssfsheet;
import org.apache.poi.hssf.usermodel.hssfworkbook;
import org.apache.poi.poifs.filesystem.poifsfilesystem;

/**
 * 操作excel表格的功能类
 */
public class excelreader {
    private poifsfilesystem fs;
    private hssfworkbook wb;
    private hssfsheet sheet;
    private hssfrow row;

    /**
     * 读取excel表格表头的内容
     * @param inputstream
     * @return string 表头内容的数组
     */
    public string[] readexceltitle(inputstream is) {
        try {
            fs = new poifsfilesystem(is);
            wb = new hssfworkbook(fs);
        } catch (ioexception e) {
            e.printstacktrace();
        }
        sheet = wb.getsheetat(0);
        row = sheet.getrow(0);
        // 标题总列数
        int colnum = row.getphysicalnumberofcells();
        system.out.println("colnum:" + colnum);
        string[] title = new string[colnum];
        for (int i = 0; i < colnum; i++) {
            //title[i] = getstringcellvalue(row.getcell((short) i));
            title[i] = getcellformatvalue(row.getcell((short) i));
        }
        return title;
    }

    /**
     * 读取excel数据内容
     * @param inputstream
     * @return map 包含单元格数据内容的map对象
     */
    public map readexcelcontent(inputstream is) {
        map content = new hashmap();
        string str = "";
        try {
            fs = new poifsfilesystem(is);
            wb = new hssfworkbook(fs);
        } catch (ioexception e) {
            e.printstacktrace();
        }
        sheet = wb.getsheetat(0);
        // 得到总行数
        int rownum = sheet.getlastrownum();
        row = sheet.getrow(0);
        int colnum = row.getphysicalnumberofcells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rownum; i++) {
            row = sheet.getrow(i);
            int j = 0;
            while (j < colnum) {
                // 每个单元格的数据内容用"-"分割开,以后需要时用string类的replace()方法还原数据
                // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
                // str += getstringcellvalue(row.getcell((short) j)).trim() +
                // "-";
                str += getcellformatvalue(row.getcell((short) j)).trim() + "    ";
                j++;
            }
            content.put(i, str);
            str = "";
        }
        return content;
    }

    /**
     * 获取单元格数据内容为字符串类型的数据
     * 
     * @param cell excel单元格
     * @return string 单元格数据内容
     */
    private string getstringcellvalue(hssfcell cell) {
        string strcell = "";
        switch (cell.getcelltype()) {
        case hssfcell.cell_type_string:
            strcell = cell.getstringcellvalue();
            break;
        case hssfcell.cell_type_numeric:
            strcell = string.valueof(cell.getnumericcellvalue());
            break;
        case hssfcell.cell_type_boolean:
            strcell = string.valueof(cell.getbooleancellvalue());
            break;
        case hssfcell.cell_type_blank:
            strcell = "";
            break;
        default:
            strcell = "";
            break;
        }
        if (strcell.equals("") || strcell == null) {
            return "";
        }
        if (cell == null) {
            return "";
        }
        return strcell;
    }

    /**
     * 获取单元格数据内容为日期类型的数据
     * 
     * @param cell
     *            excel单元格
     * @return string 单元格数据内容
     */
    private string getdatecellvalue(hssfcell cell) {
        string result = "";
        try {
            int celltype = cell.getcelltype();
            if (celltype == hssfcell.cell_type_numeric) {
                date date = cell.getdatecellvalue();
                result = (date.getyear() + 1900) + "-" + (date.getmonth() + 1)
                        + "-" + date.getdate();
            } else if (celltype == hssfcell.cell_type_string) {
                string date = getstringcellvalue(cell);
                result = date.replaceall("[年月]", "-").replace("日", "").trim();
            } else if (celltype == hssfcell.cell_type_blank) {
                result = "";
            }
        } catch (exception e) {
            system.out.println("日期格式不正确!");
            e.printstacktrace();
        }
        return result;
    }

    /**
     * 根据hssfcell类型设置数据
     * @param cell
     * @return
     */
    private string getcellformatvalue(hssfcell cell) {
        string cellvalue = "";
        if (cell != null) {
            // 判断当前cell的type
            switch (cell.getcelltype()) {
            // 如果当前cell的type为numeric
            case hssfcell.cell_type_numeric:
            case hssfcell.cell_type_formula: {
                // 判断当前的cell是否为date
                if (hssfdateutil.iscelldateformatted(cell)) {
                    // 如果是date类型则,转化为data格式

                    //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
                    //cellvalue = cell.getdatecellvalue().tolocalestring();

                    //方法2:这样子的data格式是不带带时分秒的:2011-10-12
                    date date = cell.getdatecellvalue();
                    simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
                    cellvalue = sdf.format(date);

                }
                // 如果是纯数字
                else {
                    // 取得当前cell的数值
                    cellvalue = string.valueof(cell.getnumericcellvalue());
                }
                break;
            }
            // 如果当前cell的type为strin
            case hssfcell.cell_type_string:
                // 取得当前的cell字符串
                cellvalue = cell.getrichstringcellvalue().getstring();
                break;
            // 默认的cell值
            default:
                cellvalue = " ";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;

    }

    public static void main(string[] args) {
        try {
            // 对读取excel表格标题测试
            inputstream is = new fileinputstream("d:\\test2.xls");
            excelreader excelreader = new excelreader();
            string[] title = excelreader.readexceltitle(is);
            system.out.println("获得excel表格的标题:");
            for (string s : title) {
                system.out.print(s + " ");
            }

            // 对读取excel表格内容测试
            inputstream is2 = new fileinputstream("d:\\test2.xls");
            map map = excelreader.readexcelcontent(is2);
            system.out.println("获得excel表格的内容:");
            for (int i = 1; i <= map.size(); i++) {
                system.out.println(map.get(i));
            }

        } catch (filenotfoundexception e) {
            system.out.println("未找到指定路径的文件!");
            e.printstacktrace();
        }
    }
}

3.总结
因为excel单元格中的内容往往都有一定的格式,比如日期型,数字型,字符串型,因此在读取的时候要进行格式判断,不然会出现错误。常见的就是不能正常读取日期。在代码实例中有一个方法:
getcellformatvalue(hssfcell cell)
往这个方法中传入excel单元格就能识别单元格格式,并转化为正确的格式。
ps:2012-2-23
代码实例中有一段代码:
int colnum = row.getphysicalnumberofcells();

其中的hssfrow.getphysicalnumberofcells();这个方法是用于获取一行中存在的单元格数,poi的官方api中有给出getphysicalnumberofcells方法的解释
String excelDir ="c:/tep.xls"; //excel路径
FileInputStream finput = new FileInputStream("excelDir" );
POIFSFileSystem fs = new POIFSFileSystem( finput );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0); //参数 0 代表第一个sheet 
HSSFRow row = sheet.getRow((short)0); //得到第一行
HSSFCell cell = row .getCell( (short) 0); //得到第一列
System.out.println(cell.getNumericCellValue()); //得到第一行第一列的单元格内容. 分数是数字型,注意内容的类型.
 获取颜色好像没办法

相关问答

更多
  • poi好像不能读取超过128列的数据,不知道是不是我记错了一直用的jxl,但是网上和官方发布的jxl有个致命缺陷,是编码问题,需要自己更改代码,再重编译jxl包,我建议你用poi吧,一般poi编码不会有问题的。 言归正传jxl设计的时候不是将颜色等信息直接设计到单元格Cell类中,而是通过一个CellFormat存储各个属性 Workbook book = Workbook.getWorkbook(new File("fileName")); 读取你的文件Sheet sheet = book.getShee ...
  • 也不是没有办法的,POI或JXL这些组件也是用纯JAVA来写的,不依靠它们相当于用JAVA来实现它们的部份功能。具体办法得研究一下他们的源码才能知道。
  • package edu.sjtu.erplab.poi; import java.io.InputStream&ch=ww.xqy.chain" target="_blank" class="link-baike">FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; im ...
  • 您必须提供双倍的价值。 正如文件所说 : setCellValue public void setCellValue(double value) 为单元格设置一个数值 参数 : 值 - 将此单元格设置为的数值。 对于公式,我们将设置预先计算的值,对于数字我们将设置其值。 对于其他类型,我们将把单元格更改为数字单元格并设置其值。 所以,它应该是 dCell.setCellValue(new Double("123")); 要么 dCell.setCellValue(123); //Remember, th ...
  • 一个单色的单元格永远不能为空。 它必须存在。 所以我们只能循环现有的单元格。 每个定义的CellStyle不为空。 但是如果没有颜色, CellStyle.getFillForegroundColorColor可以返回null。 所以我们需要检查。 假设下面的表格: 码: import org.apache.poi.ss.usermodel.*; import java.io.*; import java.util.Arrays; class ReadColorsFromExcel { public ...
  • Apache POI限制为每个工作簿32767个字体 您需要找到一种重用字体和单元格样式的方法。 Apache POI is limited to 32767 Fonts per workbook You will need to find a way to reuse the fonts and cell styles.
  • 我将此作为unicode粘贴到xls文件的单元格A1:

    This is a test. Will this text be bold or italic

    这个html行产生了这个: 这是一个测试。 这个文本是粗体还是斜体 我的代码: public class ExcelWithHtml { //

    This is a test. Will this text be bold or // ...

  • 打开xlsx文件选择列,右键单击单元格 - >格式化单元格...-> custom-> type = 0.00000000000单击确定。 现在无论你在那个单元格上写什么,它都将以该格式打印,如果你选择它也会显示总和。 按代码 import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi ...
  • 我认为由于Excel 2003调色板仅包含56种颜色,因此无法获得单元格的确切颜色。 我发现获得确切颜色的独特方式是,当您在Excel的选项中将Excel格式保存为.xls,然后在保存菜单中,我们可以更改所需颜色的调色板颜色。 I think that it isn´t possible to obtain the exact color of the cell because of Excel 2003 palette contains only 56 colors. The unique way tha ...
  • 您可以使用CellReference来解析所需的String,这是一个示例: String[] cellStrings = "A2:A8".split(":"); CellReference start = new CellReference(cellStrings[0]); CellReference end = new CellReference(cellStrings[1]); CellRangeAddress address = new CellRangeAddre ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)