Пример #1
0
        private static void CreateRows(this HSSFWorkbook workbook, DataRowCollection rows, Dictionary <string, string> columns, string sheetName = "Sheet")
        {
            HSSFCellStyle headStyle  = workbook.SetHeaderStyle();
            HSSFCellStyle cellStyle  = workbook.SetCellStyle();
            short         dateFormat = workbook.SetDateFormat();

            //行首
            HSSFSheet sheet = workbook.CreateSheet(sheetName);

            sheet.CreateHeader(columns, headStyle);

            int rowCount   = 1;
            int sheetCount = 1;

            foreach (DataRow dr in rows)
            {
                //超出10000条数据 创建新的工作簿
                if (rowCount == 65536)
                {
                    rowCount = 1;
                    sheetCount++;
                    sheet = workbook.CreateSheet(sheetName + sheetCount);
                    sheet.CreateHeader(columns, headStyle);
                }
                HSSFRow row = sheet.CreateRow(rowCount);
                row.CreateCells(dr, columns, cellStyle, dateFormat);
                rowCount++;
            }
        }
Пример #2
0
        private static void CreateCells <T>(this HSSFWorkbook workbook, HSSFRow row, Dictionary <string, string> columns, T item, HSSFCellStyle cellStyle)
        {
            Type type = typeof(T);

            PropertyInfo[] propertyInfos = type.GetProperties();
            int            index         = 0;

            foreach (KeyValuePair <string, string> entry in columns)
            {
                PropertyInfo info = propertyInfos.First(p => String.Equals(p.Name, entry.Key, StringComparison.CurrentCultureIgnoreCase));
                if (info == null)
                {
                    continue;
                }

                var   cell       = row.CreateCell(index);
                var   obj        = info.GetValue(item, null);
                short dateFormat = workbook.SetDateFormat();
                cell.SetCellValue(obj.GetType(), obj.ToString(), cellStyle, dateFormat);

                index++;
            }
        }