Procházet zdrojové kódy

导入,适配开发

chenyongxing před 8 roky
rodič
revize
49d625e4e6

+ 39 - 0
src/main/java/com/yihu/hos/standard/util/ExcelModel.java

@ -0,0 +1,39 @@
package com.yihu.hos.standard.util;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Administrator on 2016/6/24.
 */
public class ExcelModel {
    public static String[] dataset={"平台数据集编码","平台数据集名称","数据元编码","数据元名称","机构数据集编码","机构数据集名称","机构数据元编码","机构数据元名称","说明"};
    public static String[] dict={"平台字典编码","平台字典名称","字典項编码","字典項名称","机构字典编码","机构字典名称","机构字典項编码","机构字典項名称","说明"};
    private String sheetName;//sheet名字
    private List<String> head =new ArrayList<String>();//表头名字
    private List<List<String>> context=new ArrayList<List<String>>();//内容
    public String getSheetName() {
        return sheetName;
    }
    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }
    public List<String> getHead() {
        return head;
    }
    public void setHead(List<String> head) {
        this.head = head;
    }
    public List<List<String>> getContext() {
        return context;
    }
    public void setContext(List<List<String>> context) {
        this.context = context;
    }
}

+ 116 - 0
src/main/java/com/yihu/hos/standard/util/ExcelUtil.java

@ -0,0 +1,116 @@
package com.yihu.hos.standard.util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.IndexedColors;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
/**
 * Created by Administrator on 2016/6/24.
 */
public class ExcelUtil {
    public static void downFileByHttpResponse(HttpServletResponse response, List<ExcelModel> excelModels) throws Exception {
        response.setHeader("Content-disposition", "attachment; filename= adapt.xlsx");// 设定输出文件头
        response.setContentType("application/x-msdownload");// 定义输出类型
        OutputStream os = response.getOutputStream();// 取得输出流
        HSSFWorkbook xssfWorkbook = new HSSFWorkbook();
        HSSFCellStyle style=xssfWorkbook.createCellStyle();
        for (ExcelModel excelModel : excelModels) {
            HSSFSheet sheet = xssfWorkbook.createSheet(excelModel.getSheetName());
            //设置表头
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < excelModel.getHead().size(); i++) {
                sheet.setColumnWidth(i, 5000);
                HSSFCell cell= row.createCell(i);
                style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());//設置背景色
                style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
                HSSFFont font = xssfWorkbook.createFont();
                font.setFontName("黑体");
                font.setFontHeightInPoints((short) 12);
                style.setFont(font);
                cell.setCellStyle(style);
                cell.setCellValue(excelModel.getHead().get(i));
            }
            for (int i = 0; i <excelModel.getContext().size(); i++) {
                List<String> rowData = excelModel.getContext().get(i);
                row = sheet.createRow(i + 1);
                for (int j = 0; j < rowData.size(); j++) {
                    HSSFCell cell= row.createCell(j);
                    cell.setCellValue(rowData.get(j));
                }
            }
        }
        //主体内容生成结束
        xssfWorkbook.write(os); // 写入文件
        xssfWorkbook.close();
        os.flush();
        os.close();
    }
    public static File saveAsFile(List<ExcelModel> excelModels,String path) throws Exception {
        File newPath=new File(path);
        newPath.mkdir();
        File file=new File(path+ UUID.randomUUID().toString().replaceAll("-", "")+".xls");
        OutputStream outputStream=new FileOutputStream(file);
        HSSFWorkbook xssfWorkbook = new HSSFWorkbook();
        HSSFCellStyle style=xssfWorkbook.createCellStyle();
        for (ExcelModel excelModel : excelModels) {
            HSSFSheet sheet = xssfWorkbook.createSheet(excelModel.getSheetName());
            //设置表头
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < excelModel.getHead().size(); i++) {
                sheet.setColumnWidth(i, 5000);
                HSSFCell cell= row.createCell(i);
                style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());//設置背景色
                style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
                HSSFFont font = xssfWorkbook.createFont();
                font.setFontName("黑体");
                font.setFontHeightInPoints((short) 12);
                style.setFont(font);
                cell.setCellStyle(style);
                cell.setCellValue(excelModel.getHead().get(i));
            }
            for (int i = 0; i <excelModel.getContext().size(); i++) {
                List<String> rowData = excelModel.getContext().get(i);
                row = sheet.createRow(i + 1);
                for (int j = 0; j < rowData.size(); j++) {
                    HSSFCell cell= row.createCell(j);
                    cell.setCellValue(rowData.get(j));
                }
            }
        }
        //主体内容生成结束
         xssfWorkbook.write(outputStream); // 写入文件
         xssfWorkbook.close();
         outputStream.flush();
         outputStream.close();
        return file;
    }
}

+ 452 - 0
src/main/java/com/yihu/hos/standard/util/ExcelUtilBigData.java

@ -0,0 +1,452 @@
package com.yihu.hos.standard.util;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by Administrator on 2016/7/4.
 */
public class ExcelUtilBigData {
    /**
     * The type of the data value is indicated by an attribute on the cell. The
     * value is usually in a "v" element within the cell.
     */
    enum xssfDataType {
        BOOL, ERROR, FORMULA, INLINESTR, SSTINDEX, NUMBER,
    }
    /**
     * 使用xssf_sax_API处理Excel,请参考: http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
     * <p/>
     * Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at
     * http://www.ecma-international.org/publications/standards/Ecma-376.htm
     * <p/>
     * A web-friendly version is http://openiso.org/Ecma/376/Part4
     */
    class MyXSSFSheetHandler extends DefaultHandler {
        /**
         * Table with styles
         */
        private StylesTable stylesTable;
        /**
         * Table with unique strings
         */
        private ReadOnlySharedStringsTable sharedStringsTable;
        /**
         * Destination for data
         */
        private final PrintStream output;
        /**
         * Number of columns to read starting with leftmost
         */
        private final int minColumnCount;
        // Set when V start element is seen
        private boolean vIsOpen;
        // Set when cell start element is seen;
        // used when cell close element is seen.
        private xssfDataType nextDataType;
        // Used to format numeric cell values.
        private short formatIndex;
        private String formatString;
        private final DataFormatter formatter;
        private int thisColumn = -1;
        // The last column printed to the output stream
        private int lastColumnNumber = -1;
        // Gathers characters as they are seen.
        private StringBuffer value;
        private String[] record;
        private List<String[]> rows = new ArrayList<String[]>();
        private boolean isCellNull = false;
        private int start;
        /**
         * Accepts objects needed while parsing.
         *
         * @param styles  Table of styles
         * @param strings Table of shared strings
         * @param cols    Minimum number of columns to show
         * @param target  Sink for output
         */
        public MyXSSFSheetHandler(StylesTable styles,
                                  ReadOnlySharedStringsTable strings, int cols, PrintStream target,int start) {
            this.stylesTable = styles;
            this.sharedStringsTable = strings;
            this.minColumnCount = cols;
            this.output = target;
            this.value = new StringBuffer();
            this.nextDataType = xssfDataType.NUMBER;
            this.formatter = new DataFormatter();
            record = new String[this.minColumnCount];
            this.start=start;
            rows.clear();// 每次读取都清空行集合
        }
        /*
         * (non-Javadoc)
         *
         * @see
         * org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         * java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        public void startElement(String uri, String localName, String name,
                                 Attributes attributes) throws SAXException {
            if ("inlineStr".equals(name) || "v".equals(name)) {
                vIsOpen = true;
                // Clear contents cache
                value.setLength(0);
            }
            // c => cell
            else if ("c".equals(name)) {
                // Get the cell reference
                String r = attributes.getValue("r");
                int firstDigit = -1;
                for (int c = 0; c < r.length(); ++c) {
                    if (Character.isDigit(r.charAt(c))) {
                        firstDigit = c;
                        break;
                    }
                }
                thisColumn = nameToColumn(r.substring(0, firstDigit));
                // Set up defaults.
                this.nextDataType = xssfDataType.NUMBER;
                this.formatIndex = -1;
                this.formatString = null;
                String cellType = attributes.getValue("t");
                String cellStyleStr = attributes.getValue("s");
                if ("b".equals(cellType))
                    nextDataType = xssfDataType.BOOL;
                else if ("e".equals(cellType))
                    nextDataType = xssfDataType.ERROR;
                else if ("inlineStr".equals(cellType))
                    nextDataType = xssfDataType.INLINESTR;
                else if ("s".equals(cellType))
                    nextDataType = xssfDataType.SSTINDEX;
                else if ("str".equals(cellType))
                    nextDataType = xssfDataType.FORMULA;
                else if (cellStyleStr != null) {
                    // It's a number, but almost certainly one
                    // with a special style or format
                    int styleIndex = Integer.parseInt(cellStyleStr);
                    XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
                    this.formatIndex = style.getDataFormat();
                    this.formatString = style.getDataFormatString();
                    if (this.formatString == null)
                        this.formatString = BuiltinFormats
                                .getBuiltinFormat(this.formatIndex);
                }
            }
        }
        /*
         * (non-Javadoc)
         *
         * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
         * java.lang.String, java.lang.String)
         */
        public void endElement(String uri, String localName, String name)
                throws SAXException {
            String thisStr = null;
            // v => contents of a cell
            if ("v".equals(name)) {
                // Process the value contents as required.
                // Do now, as characters() may be called more than once
                switch (nextDataType) {
                    case BOOL:
                        char first = value.charAt(0);
                        thisStr = first == '0' ? "FALSE" : "TRUE";
                        break;
                    case ERROR:
                        thisStr = "\"ERROR:" + value.toString() + '"';
                        break;
                    case FORMULA:
                        // A formula could result in a string value,
                        // so always add double-quote characters.
                        thisStr = '"' + value.toString() + '"';
                        break;
                    case INLINESTR:
                        // TODO: have seen an example of this, so it's untested.
                        XSSFRichTextString rtsi = new XSSFRichTextString(
                                value.toString());
                        thisStr = '"' + rtsi.toString() + '"';
                        break;
                    case SSTINDEX:
                        String sstIndex = value.toString();
                        try {
                            int idx = Integer.parseInt(sstIndex);
                            XSSFRichTextString rtss = new XSSFRichTextString(
                                    sharedStringsTable.getEntryAt(idx));
                            thisStr = '"' + rtss.toString() + '"';
                        } catch (NumberFormatException ex) {
                            output.println("Failed to parse SST index '" + sstIndex
                                    + "': " + ex.toString());
                        }
                        break;
                    case NUMBER:
                        String n = value.toString();
                        // 判断是否是日期格式
                        if (HSSFDateUtil.isADateFormat(this.formatIndex, n)) {
                            Double d = Double.parseDouble(n);
                            Date date = HSSFDateUtil.getJavaDate(d);
                            thisStr = formateDateToString(date);
                        } else if (this.formatString != null)
                            thisStr = formatter.formatRawCellContents(
                                    Double.parseDouble(n), this.formatIndex,
                                    this.formatString);
                        else
                            thisStr = n;
                        break;
                    default:
                        thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
                        break;
                }
                // Output after we've seen the string contents
                // Emit commas for any fields that were missing on this row
                if (lastColumnNumber == -1) {
                    lastColumnNumber = 0;
                }
                //判断单元格的值是否为空
                if (thisStr == null || "".equals(thisStr)) {
                   // if(start==0){
                        isCellNull = true;// 设置单元格是否为空值
                    //}else{
                    //    if(thisColumn>3){
                    //        isCellNull = true;// 设置单元格是否为空值
                    //    }
                    // }
                }
                record[thisColumn] = thisStr;
                // Update column
                if (thisColumn > -1)
                    lastColumnNumber = thisColumn;
            } else if ("row".equals(name)) {
                // Print out any missing commas if needed
                if (minColumns > 0) {
                    // Columns are 0 based
                    if (lastColumnNumber == -1) {
                        lastColumnNumber = 0;
                    }
                    //if(start==0){
                        if (isCellNull == false )// 判断是否空行
                        {
                            rows.add(record.clone());
                            isCellNull = false;
                            for (int i = 0; i < record.length; i++) {
                                record[i] = null;
                            }
                        }
                   // }else{
//                        if (isCellNull == false && record[4] != null
//                                && record[3] != null)// 判断是否空行
//                        {
//                            rows.add(record.clone());
//                            isCellNull = false;
//                            for (int i = 0; i < record.length; i++) {
//                                record[i] = null;
//                            }
//                        }
//                    }
                }
                lastColumnNumber = -1;
            }
        }
        public List<String[]> getRows() {
            return rows;
        }
        public void setRows(List<String[]> rows) {
            this.rows = rows;
        }
        /**
         * Captures characters only if a suitable element is open. Originally
         * was just "v"; extended for inlineStr also.
         */
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            if (vIsOpen)
                value.append(ch, start, length);
        }
        /**
         * Converts an Excel column name like "C" to a zero-based index.
         *
         * @param name
         * @return Index corresponding to the specified name
         */
        private int nameToColumn(String name) {
            int column = -1;
            for (int i = 0; i < name.length(); ++i) {
                int c = name.charAt(i);
                column = (column + 1) * 26 + c - 'A';
            }
            return column;
        }
        private String formateDateToString(Date date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化日期
            return sdf.format(date);
        }
    }
    // /////////////////////////////////////
    private OPCPackage xlsxPackage;
    private int minColumns;
    private PrintStream output;
    private int start;
    /**
     * Creates a new XLSX -> CSV converter
     *
     * @param pkg        The XLSX package to process
     * @param output     The PrintStream to output the CSV to
     * @param minColumns The minimum number of columns to output, or -1 for no minimum
     */
    public ExcelUtilBigData(OPCPackage pkg, PrintStream output,
                            int minColumns, int start) {
        this.xlsxPackage = pkg;
        this.output = output;
        this.minColumns = minColumns;
        this.start=start;
    }
    /**
     * Parses and shows the content of one sheet using the specified styles and
     * shared-strings tables.
     *
     * @param styles
     * @param strings
     * @param sheetInputStream
     */
    public List<String[]> processSheet(StylesTable styles,
                                       ReadOnlySharedStringsTable strings, InputStream sheetInputStream)
            throws IOException, ParserConfigurationException, SAXException {
        InputSource sheetSource = new InputSource(sheetInputStream);
        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxFactory.newSAXParser();
        XMLReader sheetParser = saxParser.getXMLReader();
        MyXSSFSheetHandler handler = new MyXSSFSheetHandler(styles, strings,
                    this.minColumns, this.output,this.start);
        sheetParser.setContentHandler(handler);
        sheetParser.parse(sheetSource);
        return handler.getRows();
    }
    /**
     * 初始化这个处理程序 将
     *
     * @throws IOException
     * @throws OpenXML4JException
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    public List<List<String[]>> process() throws IOException, OpenXML4JException,
            ParserConfigurationException, SAXException {
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(
                this.xlsxPackage);
        XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
        List<List<String[]>> returnlist = new ArrayList<List<String[]>>();
        List<String[]> list=null;
        StylesTable styles = xssfReader.getStylesTable();
        XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader
                .getSheetsData();
        int index = 0;
        while (iter.hasNext()) {
            InputStream stream = iter.next();
            list = processSheet(styles, strings, stream);
            returnlist.add(list);
            stream.close();
            ++index;
        }
        return returnlist;
    }
    /**
     * 读取Excel
     *
     * @param in       文件路径
     * @param minColumns 列总数
     * @param start 判断起始行
     * @return
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws OpenXML4JException
     * @throws IOException
     */
    public static List<List<String[]>> readerExcel(InputStream
                                                           in, int minColumns,int start) throws IOException, OpenXML4JException,
            ParserConfigurationException, SAXException {
        OPCPackage p = OPCPackage.open(in);
        ExcelUtilBigData xlsx2csv = new ExcelUtilBigData(p, System.out,
                minColumns,start);
        List<List<String[]>> returnList = xlsx2csv.process();
        p.close();
        return returnList;
    }
//    public static void main(String[] args) throws Exception {
//        List<List<String[]>> list = ExcelUtilBigData
//                .readerExcel("F:\\公司\\健康之路\\工作文档\\标准编辑器\\机构数据字典.xlsx", 3);
//        for (List<String[]> l:list){
//            for (String[] record : l) {
//                for (String cell : record) {
//                    System.out.print(cell + "  ");
//                }
//                System.out.println();
//            }
//        }
  //  }
}

+ 100 - 0
src/main/java/com/yihu/hos/standard/util/GetChineseFirst.java

@ -0,0 +1,100 @@
package com.yihu.hos.standard.util;
/**
 * Created by Administrator on 2016/6/28.
 */
public class GetChineseFirst {
    // 简体中文的编码范围从B0A1(45217)一直到F7FE(63486)
    private static int BEGIN = 45217;
    private static int END = 63486;
    // 按照声 母表示,这个表是在GB2312中的出现的第一个汉字,也就是说“啊”是代表首字母a的第一个汉字。
    // i, u, v都不做声母, 自定规则跟随前面的字母
    private static char[] chartable = { '啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈', '击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然', '撒', '塌', '塌', '塌', '挖', '昔', '压', '匝', };
    // 二十六个字母区间对应二十七个端点
    // GB2312码汉字区间十进制表示
    private static int[] table = new int[27];
    // 对应首字母区间表
    private static char[] initialtable = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 't', 't', 'w', 'x', 'y', 'z', };
    // 初始化
    static {
        for (int i = 0; i < 26; i++) {
            table[i] = gbValue(chartable[i]);// 得到GB2312码的首字母区间端点表,十进制。
        }
        table[26] = END;// 区间表结尾
    }
    // ------------------------public方法区------------------------
    // 根据一个包含汉字的字符串返回一个汉字拼音首字母的字符串 最重要的一个方法,思路如下:一个个字符读入、判断、输出
    public static String cn2py(String SourceStr) {
        String Result = "";
        int StrLength = SourceStr.length();
        int i;
        try {
            for (i = 0; i < StrLength; i++) {
                Result += Char2Initial(SourceStr.charAt(i));
            }
        } catch (Exception e) {
            Result = "";
            e.printStackTrace();
        }
        return Result;
    }
    // ------------------------private方法区------------------------
    /**
     * 输入字符,得到他的声母,英文字母返回对应的大写字母,其他非简体汉字返回 '0'   *   
     */
    private static char Char2Initial(char ch) {
        // 对英文字母的处理:小写字母转换为大写,大写的直接返回
        if (ch >= 'a' && ch <= 'z') {
            return (char) (ch - 'a' + 'A');
        }
        if (ch >= 'A' && ch <= 'Z') {
            return ch;
        }
        // 对非英文字母的处理:转化为首字母,然后判断是否在码表范围内,
        // 若不是,则直接返回。
        // 若是,则在码表内的进行判断。
        int gb = gbValue(ch);// 汉字转换首字母
        if ((gb < BEGIN) || (gb > END))// 在码表区间之前,直接返回
        {
            return ch;
        }
        int i;
        for (i = 0; i < 26; i++) {// 判断匹配码表区间,匹配到就break,判断区间形如“[,)”
            if ((gb >= table[i]) && (gb < table[i + 1])) {
                break;
            }
        }
        if (gb == END) {// 补上GB2312区间最右端
            i = 25;
        }
        return initialtable[i]; // 在码表区间中,返回首字母
    }
    /**
     * 取出汉字的编码 cn 汉字   
     */
    private static int gbValue(char ch) {// 将一个汉字(GB2312)转换为十进制表示。
        String str = new String();
        str += ch;
        try {
            byte[] bytes = str.getBytes("GB2312");
            if (bytes.length < 2) {
                return 0;
            }
            return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff);
        } catch (Exception e) {
            return 0;
        }
    }
    public static void main(String[] args) throws Exception {
       // System.out.println(cn2py("陈伟达"));
    }
}

+ 28 - 0
src/main/java/com/yihu/hos/standard/util/LikeHashMap.java

@ -0,0 +1,28 @@
package com.yihu.hos.standard.util;
import java.util.*;
/**
 * Created by Administrator on 2016/7/13.
 */
public class LikeHashMap<K, V> extends HashMap<K, V> {
    public V get(String key, boolean like) {
        List<V> list = null;
        if (like) {
            list = new ArrayList<V>();
            K[] a = null;
            Set<K> set = this.keySet();
            a = (K[])set.toArray();
            Arrays.sort(a, null);
            for (int i = 0; i < a.length; i++) {
                if (a[i].toString().indexOf(key) == -1) {
                    continue;
                } else {
                   return this.get(a[i]);
                }
            }
        }
        return null;
    }
}