Exemple #1
0
 public void chuchushuju()
 {
     try
     {
         string path = PathHelper.dataPath + @"\Measure\" + tjcjg.Year.ToString() + tjcjg.Month.ToString() + tjcjg.Day.ToString() + tjcjg.Hour.ToString() + tjcjg.Minute.ToString() + tjcjg.Second.ToString() + ".xls";
         using (FileStream fs = File.OpenWrite(path))
         {
             sheetc  = 0;
             sheetrr = sheet.CreateRow(0);
             sheetcc = sheetrr.CreateCell(sheetc);
             sheetcc.SetCellValue("序号(NUMBER)");
             sheetc += 1;
             sheetcc = sheetrr.CreateCell(sheetc);
             sheetcc.SetCellValue("测量时间(MESURE TIME)");
             foreach (jiancejieguo jcjg3 in jcjg2)
             {
                 sheetc += 1;
                 sheetcc = sheetrr.CreateCell(sheetc);
                 sheetcc.SetCellValue(jcjg3.jiancexiangmu);
             }
             wkb.Write(fs);//向打开的这个xls文件中写入并保存。
             wkb.Clear();
             sheetr  = 0; sheetc = 0;
             sheet   = wkb.CreateSheet("检测结果(Measure Data)");
             tjcjg   = DateTime.Now;
             sheetrr = sheet.CreateRow(sheetr);
             sheetcc = sheetrr.CreateCell(sheetc);
         }
     }
     catch
     {
     }
     finally { }
 }
        public static void Free()                   //释放资源
        {
            if (workbook != null)
            {
                workbook.Clear();

                workbook.Close();

                workbook = null;
            }
        }
Exemple #3
0
        private void WriteToFile()
        {
            string year = DateTime.Now.Year.ToString();
            //string path = HttpContext.Current.Server.MapPath(DateTime.Now.ToString("yyyyMMddmmss") + ".xls");
            string     path = "d:\\a.xls";
            FileStream file = new FileStream(path, FileMode.Create);

            _hssfworkbook.Write(file);
            file.Close();

            _hssfworkbook.Clear();
        }
 protected override void Dispose(bool Disposing)
 {
     hssfworkbook.Clear();
 }
        private void ListWriteExcelFile(int allRows, int sheetCount, ExportFileInfo exportFileInfo, string filePath, List <T> list, CancellationToken token, ref int currectListOccupancyRows, ref int dispId, Action <int> exportProgressAction)
        {
            int currectSheetOccupancyRows = Pub.DEFAULT_EXCELEXPORT_SHEET_MAXCOUNT;
            int sheetIdx          = 1;
            int currectExcelIdx   = 0; //当前excel操作行下标
            int currectExcelCount = 0;
            var workbook          = new HSSFWorkbook();

            try
            {
                var sheet = CreateSheet(workbook, sheetCount, sheetIdx, exportFileInfo.ExcelTitle, out currectExcelIdx);

                int singleExcelMaxCount = Math.Min(Pub.DEFAULT_EXCEL_MAXCOUNT_FORINFO, allRows);
                while (currectExcelCount < singleExcelMaxCount)
                {
                    token.ThrowIfCancellationRequested();
                    int readerCount = Math.Min(Pub.DEFAULT_EXCELEXPORT_SHEET_MAXCOUNT, currectListOccupancyRows);
                    readerCount = Math.Min(readerCount, currectSheetOccupancyRows);

                    if (readerCount > 0)
                    {
                        var readList   = list.GetRange(0, readerCount);
                        int writeCount = 0;
                        sheet = ListToSheet(workbook, sheet, readList, ref dispId, ref currectExcelIdx, exportProgressAction, token, out writeCount);
                        list.RemoveRange(0, readerCount);

                        singleExcelMaxCount      -= readerCount;
                        currectListOccupancyRows -= readerCount;

                        currectExcelCount += writeCount;
                    }

                    #region state update

                    if (currectListOccupancyRows <= 0 || readerCount == 0)
                    {
                        break;
                    }

                    if (singleExcelMaxCount >= Pub.DEFAULT_EXCEL_MAXCOUNT_FORINFO)
                    {
                        //Excel满了,退出当前Excel文件
                        break;
                    }

                    //切换Sheet
                    if ((singleExcelMaxCount > 0 && singleExcelMaxCount % Pub.DEFAULT_EXCELEXPORT_SHEET_MAXCOUNT == 0) || (currectSheetOccupancyRows == 0))
                    {
                        if (sheetIdx == sheetCount)
                        {
                            break;
                        }

                        sheet.ForceFormulaRecalculation = true;
                        sheetIdx++;
                        sheet = CreateSheet(workbook, sheetCount, sheetIdx, exportFileInfo.ExcelTitle, out currectExcelIdx);
                        currectSheetOccupancyRows = Pub.DEFAULT_EXCEL_MAXCOUNT_FORINFO - singleExcelMaxCount;
                    }
                    #endregion
                }

                WriteWorkbookToFile(workbook, filePath);
            }
            finally
            {
                workbook.Clear();
                workbook = null;
                GC.Collect();
            }
        }
        private void QueryDataReaderWriteExcel(MySqlConnection conn, int allRows, int sheetCount, ExportFileInfo exportFileInfo, string filePath, CancellationToken token, string querySqlPart, List <string> tableNameList, List <int> tableCountList, string whereSqlPart, ref int tableIndex, ref int currectTableOccupancyRows, ref int currectTableStartRowIdx, ref int dispId, Action <int> exportProgressAction)
        {
            int currectSheetOccupancyRows = Pub.DEFAULT_EXCELEXPORT_SHEET_MAXCOUNT;
            int sheetIdx          = 1; //sheet下标
            int currectExcelIdx   = 0; //操作的excel操作行下标
            int currectExcelCount = 0;
            var workbook          = new HSSFWorkbook();

            try
            {
                var sheet = CreateSheet(workbook, sheetCount, sheetIdx, exportFileInfo.ExcelTitle, out currectExcelIdx);


                int singleExcelMaxCount = Math.Min(Pub.DEFAULT_EXCEL_MAXCOUNT_FORINFO, allRows);
                while (currectExcelCount < singleExcelMaxCount)
                {
                    token.ThrowIfCancellationRequested();
                    int readerCount = Math.Min(Pub.DEFAULT_EXCELEXPORT_SHEET_MAXCOUNT, currectSheetOccupancyRows);
                    readerCount = Math.Min(readerCount, currectTableOccupancyRows);

                    if (readerCount > 0)
                    {
                        string commandText = CreateQuerySqlStrAction(querySqlPart, tableNameList[tableIndex], whereSqlPart, currectTableStartRowIdx, readerCount);

                        int writeCount;
                        sheet = DataReaderToSheet(workbook, sheet, conn, commandText, ref dispId, ref currectExcelIdx, exportProgressAction, token, out writeCount);

                        singleExcelMaxCount       -= readerCount;
                        currectTableOccupancyRows -= readerCount;

                        currectTableStartRowIdx += writeCount;
                        currectExcelCount       += writeCount;
                    }

                    #region state update

                    if (currectTableOccupancyRows <= 0 || readerCount == 0)
                    {
                        //切换table
                        currectTableStartRowIdx = 0;
                        if (tableIndex == tableCountList.Count - 1)
                        {
                            break;
                        }
                        currectTableOccupancyRows = tableCountList[++tableIndex];
                    }

                    if (singleExcelMaxCount >= Pub.DEFAULT_EXCEL_MAXCOUNT_FORINFO)
                    {
                        //Excel满了,退出当前Excel文件
                        break;
                    }

                    //切换Sheet
                    if ((singleExcelMaxCount > 0 && singleExcelMaxCount % Pub.DEFAULT_EXCELEXPORT_SHEET_MAXCOUNT == 0) || (currectSheetOccupancyRows == 0))
                    {
                        if (sheetIdx == sheetCount)
                        {
                            break;
                        }

                        sheet.ForceFormulaRecalculation = true;
                        sheetIdx++;
                        sheet = CreateSheet(workbook, sheetCount, sheetIdx, exportFileInfo.ExcelTitle, out currectExcelIdx);
                        currectSheetOccupancyRows = Pub.DEFAULT_EXCEL_MAXCOUNT_FORINFO - singleExcelMaxCount;
                    }
                    #endregion
                }

                WriteWorkbookToFile(workbook, filePath);
            }
            finally
            {
                workbook.Clear();
                workbook = null;
                GC.Collect();
            }
        }
        /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        public static MemoryStream Export(DataTable dtSource, string strHeaderText)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet    sheet    = (HSSFSheet)workbook.CreateSheet();

            #region 右击文件 属性信息
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "NPOI";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author                   = "文件作者信息";  //填加xls文件作者信息
                si.ApplicationName          = "创建程序信息";  //填加xls文件创建程序信息
                si.LastAuthor               = "最后保存者信息"; //填加xls文件最后保存者信息
                si.Comments                 = "作者信息";    //填加xls文件作者信息
                si.Title                    = "标题信息";    //填加xls文件标题信息
                si.Subject                  = "主题信息";    //填加文件主题信息
                si.CreateDateTime           = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            HSSFCellStyle  dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
            HSSFDataFormat format    = (HSSFDataFormat)workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表,填充表头,填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = (HSSFSheet)workbook.CreateSheet();
                    }

                    #region 表头及样式
                    {
                        HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);

                        HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                        // headStyle.Alignment = CellHorizontalAlignment.CENTER;
                        HSSFFont font = (HSSFFont)workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight         = 700;
                        headStyle.SetFont(font);
                        headerRow.GetCell(0).CellStyle = headStyle;
                        sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
                        //  headerRow.Dis();
                    }
                    #endregion


                    #region 列头及样式
                    {
                        HSSFRow       headerRow = (HSSFRow)sheet.CreateRow(1);
                        HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                        // headStyle.Alignment = CellHorizontalAlignment.CENTER;
                        HSSFFont font = (HSSFFont)workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight         = 700;
                        headStyle.SetFont(font);
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }
                        //  headerRow.Dispose();
                    }
                    #endregion

                    rowIndex = 2;
                }
                #endregion


                #region 填充内容
                HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                    case "System.String":    //字符串类型
                        newCell.SetCellValue(drValue);
                        break;

                    case "System.DateTime":    //日期类型
                        DateTime dateV;
                        DateTime.TryParse(drValue, out dateV);
                        newCell.SetCellValue(dateV);

                        newCell.CellStyle = dateStyle;    //格式化显示
                        break;

                    case "System.Boolean":    //布尔型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        newCell.SetCellValue(boolV);
                        break;

                    case "System.Int16":    //整型
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        newCell.SetCellValue(intV);
                        break;

                    case "System.Decimal":    //浮点型
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        newCell.SetCellValue(doubV);
                        break;

                    case "System.DBNull":    //空值处理
                        newCell.SetCellValue("");
                        break;

                    default:
                        newCell.SetCellValue("");
                        break;
                    }
                }
                #endregion

                rowIndex++;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                // sheet.Dispose();
                workbook.Clear();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
                return(ms);
            }
        }