把PivotGridControl控件導出的Excel再整理(設置第一行標題,去掉合計,取消合併單元格)

/// <summary>
        /// 把PivotGridControl控件導出的Excel再整理(設置第一行標題,去掉合計,取消合併單元格)
        /// </summary>
        public static void Tidy(string filePath, string[] column,int columnCount)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            HSSFWorkbook workbook = new HSSFWorkbook(fs);
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);

            //設置第一行的標題
            for (int i = 0; i < column.Length; i++)
            {
                sheet.GetRow(0).CreateCell(i).SetCellValue(column[i]);
            }

            List<int> rowsIndex = new List<int>();          
            int rowCount = sheet.LastRowNum;
            HSSFCell cell;
            //獲取包含合計的行號
            for (int i = 0; i <= rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    cell = (HSSFCell)sheet.GetRow(i).GetCell(j);
                    if (cell != null && (cell.StringCellValue.Contains("合計") || cell.StringCellValue.Contains("總計")))
                    {
                        sheet.RemoveRow(sheet.GetRow(i));//刪除合計行至關於清空
                        rowsIndex.Add(i);
                        break;
                    }
                }
            }
           
            //刪除合計行Excel中經過單元格移動來實現
            int[] rowOfArray = rowsIndex.ToArray();
            for (int i = rowOfArray.Length - 1; i >=0; i--)
            { 
                if (rowOfArray[i] < sheet.LastRowNum)
                    sheet.ShiftRows(rowOfArray[i] + 1, sheet.LastRowNum, -1);
            }
            
             
            //填充合併的單元格
            rowCount = sheet.LastRowNum;
            for (int i = 0; i <= rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    cell = (HSSFCell)sheet.GetRow(i).GetCell(j);
                    if (cell == null)
                    {
                        cell = (HSSFCell)sheet.GetRow(i).CreateCell(j);
                        cell.SetCellValue(sheet.GetRow(i - 1).GetCell(j).StringCellValue);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(cell.StringCellValue))
                        {
                            cell.SetCellValue(sheet.GetRow(i-1).GetCell(j).StringCellValue);
                        }
                    }                     
                }
            }
         
            //寫回Excel
            using (FileStream filess = File.OpenWrite(filePath))
            {
                workbook.Write(filess);
            }

        }
相關文章
相關標籤/搜索