Aspose.Cell 導出幫助類

   /// <summary>
    /// excel 導出列輔助類
    /// </summary>
    public class Col
    { /// <summary>
      /// 中文名(顯示名稱)
      /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 英文(數據庫查詢字段)
        /// </summary>
        public string ColName { get; set; }
    }

 

public class AsposeExportExcel
    {
        /// <summary>
        /// 將list 導出excel
        /// </summary>
        /// <typeparam name="T">model</typeparam>
        /// <param name="list">需要導出的list數據集</param>
        /// <param name="sheetName">標題</param>
        /// <param name="cols">需要導出的字段</param>
        /// <returns>excel保存的路徑</returns>
        public string ExportExecl<T>(IList<T> list, string sheetName, List<Col> cols) where T : class, new()
        {
            string rptPath = AppContext.BaseDirectory + "Report/WorkNoteList.xls";
            try
            {
                #region Aspose  創建工作簿
                /*創建工作簿*/
                Workbook workbook = new Workbook(rptPath);
                Worksheet sheet = workbook.Worksheets[0]; //工作表 
                Cells cells = sheet.Cells;//單元格
                //標題
                Style title = workbook.Styles[workbook.Styles.Add()];
                title.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;//字體居中
                //  cells.Merge(0, 0, 1, cols.Count);//合併單元格     前兩個爲單元格座標 第三個參數爲合併多少行,第四個參數合併多少列  
                title.Font.Size = 25;
                title.Font.IsBold = true;//粗體   
                // 表頭
                Style header = workbook.Styles[workbook.Styles.Add()];
                header.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;//字體居中
                header.Font.Size = 14;
                header.Font.IsBold = true;//粗體   
                header.ForegroundColor = System.Drawing.Color.FromArgb(204, 204, 204);//設置背景色 可以參考顏色代碼對照表  
                header.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;//應用邊界線 左邊界線  
                header.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //應用邊界線 右邊界線  
                header.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;//應用邊界線 上邊界線  
                header.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;//應用邊界線 下邊界線  
                //邊框
                Style border = workbook.Styles[workbook.Styles.Add()];
                border.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;//字體居中
                border.IsTextWrapped = true;//單元格內容自動換行  
                border.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;//應用邊界線 左邊界線  
                border.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //應用邊界線 右邊界線  
                border.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;//應用邊界線 上邊界線  
                border.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;//應用邊界線 下邊界線  
                #endregion


                int row = 0;
                cells[row, 0].PutValue(sheetName);
                cells[row, 0].SetStyle(title);
                cells.Merge(row, 0, 1, cols.Count);
                cells.SetColumnWidth(0, 30);//設置列寬  
                //生成列名
                row++;
                for (int i = 0; i < cols.Count; i++)
                {
                    cells[row, i].PutValue(cols[i].Name);
                    cells[row, i].SetStyle(header);
                }
                //生成數據  
                if (list != null && list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        row++;
                        for (int j = 0; j < cols.Count; j++)
                        {
                            string Code = cols[j].ColName;
                             if (Code.Contains("DateTime"))
                            {
                                string code = typeof(T).GetProperty(Code).GetValue(list[i]).ToString();
                                DateTime date = DateTime.Parse(code);
                                cells[row, j].PutValue(date.ToString("yyyy-MM-dd").ToString());
                            }
                            //else if (Code == "images")
                            //{
                            //    int index = sheet.Pictures.Add(row, j, row+1, j+1, "C:\\Users\\aaa\\Pictures\\b4efae6eddc451da139cac37b6fd5266d11632ba.jpg");
                            //    Aspose.Cells.Drawing.Picture picture = sheet.Pictures[index];
                            //    picture.Placement = Aspose.Cells.Drawing.PlacementType.FreeFloating;
                            //    Aspose.Cells.Hyperlink link = picture.AddHyperlink("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1398895269,2245330748&fm=26&gp=0.jpg");
                            //    link.ScreenTip = "單擊跳轉到圖片";
                            //}
                            else
                            {
                                cells[row, j].PutValue(typeof(T).GetProperty(Code).GetValue(list[i]));
                            }
                            cells[row, j].SetStyle(border);
                        }
                    }
                }

                #region 驗證是否存在文件夾
                string path = "/Upload/";
                string rootPath = AppContext.BaseDirectory + path;
                if (!System.IO.Directory.Exists(rootPath))
                {
                    Directory.CreateDirectory(rootPath);
                }
                //刪除文件
                DirectoryInfo dir = new DirectoryInfo(rootPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目錄中所有文件和子目錄
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判斷是否文件夾
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //刪除子目錄和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //刪除指定文件
                    }
                }
                #endregion

                string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                string savePath = rootPath + FileName;
                workbook.Save(savePath);
                return "Upload/" + FileName;
            }
            catch (Exception e)
            {
                return " IListToExcel: " + e.Message;
            }
        }


        /// <summary>
        /// 導入excel 返回DataTable
        /// </summary>
        /// <param name="strFileName">excel文件地址</param>
        /// <returns>DataTable</returns>
        public System.Data.DataTable ReadExcel(String strFileName)
        {
            Workbook book = new Workbook(strFileName);
            Worksheet sheet = book.Worksheets[0];
            Cells cells = sheet.Cells;
            return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
        }
    }
 

發佈了32 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章