C# NPOI導出Excel橫向縱向顯示


        /// <summary>
        /// DataTable導出Excel(縱向導出)
        /// </summary>
        /// <param name="dataTable">數據源</param>
        /// <param name="filePath">保存的路徑</param>
        /// <param name="documentname">表名</param>
        public static void Excel2(this DataTable dataTable, string filePath, string documentname)
        {
            string sheetName = "Sheet1";
            if (dataTable == null || dataTable.Rows.Count == 0)
                throw new Exception("No data to export");

            ISheet sheet = null;
            IWorkbook workbook = null;

            try
            {
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }
                string filedocmentname = "\\File Card.xls";//文件名 using (FileStream fs = new FileStream(filePath + filedocmentname, FileMode.Create, FileAccess.Write))
                {
                    workbook = new HSSFWorkbook();
                    if (string.IsNullOrEmpty(sheetName))
                        sheetName = "Sheet1";//工作簿
                    sheet = workbook.CreateSheet(sheetName);
                    IRow row = sheet.CreateRow(0);
                    IFont font = workbook.CreateFont();
                    font.FontName = "Arial";//字體樣式
                    font.Boldweight = (short)FontBoldWeight.Bold;
                    ICellStyle headerStyle2 = workbook.CreateCellStyle();
                    headerStyle2.VerticalAlignment = VerticalAlignment.Center; //垂直居中
                    headerStyle2.WrapText = true;//自動換行
                    font.FontHeightInPoints = 9;//字體 for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        ICellStyle header= workbook.CreateCellStyle();
                        header.VerticalAlignment = VerticalAlignment.Center; //垂直居中
                        header.WrapText = true;//自動換行
                        var row1_ = sheet.CreateRow(i);//創建行
                        var cellName = row1_.CreateCell(0);//列名
                        cellName.SetCellValue(dataTable.Columns[i].ColumnName.ToString().Replace("<br />", "\n"));
                        IFont font2 = workbook.CreateFont();
                        font2.Boldweight = (short)FontBoldWeight.Bold;
                        header.SetFont(font);
                        cellName.CellStyle = header;
               //填充內容
for (int j = 0; j < dataTable.Rows.Count; j++) { var cell1_ = row1_.CreateCell(j + 1); cell1_.SetCellValue(dataTable.Rows[j][i].ToString().Replace("<br />", "\n")); cell1_.CellStyle = headerStyle2; //把樣式賦給單元格 } } //設置列寬 sheet.SetColumnWidth(0, 10 * 256+200);//列寬為10
//設置行高
//row.Height = 30 * 20;//行高為30 workbook.Write(fs); //寫入到excel } } finally { if (workbook != null) workbook.Clear(); } }
      /// <summary>
        /// DataTable導出Excel(橫向導出)
        /// </summary>
        /// <param name="dataTable">數據源</param>
        /// <param name="filePath">保存的路徑</param>
        /// <param name="documentname">表名</param>
        public static void Excel(this DataTable dataTable, string filePath, string documentname)
        {
       //datatable第一列增加序號 dataTable
= AddSeriNumToDataTable(dataTable); string sheetName = "Sheet1"; if (dataTable == null || dataTable.Rows.Count == 0) throw new Exception("No data to export"); ISheet sheet = null; IWorkbook workbook = null; try { if (Directory.Exists(filePath) == false) { Directory.CreateDirectory(filePath); } string filedocmentname = "\\List.xls";//文件名
using (FileStream fs = new FileStream(filePath + filedocmentname, FileMode.Create, FileAccess.Write)) { workbook = new HSSFWorkbook(); if (string.IsNullOrEmpty(sheetName)) sheetName = "Sheet1"; sheet = workbook.CreateSheet(sheetName); IRow row = sheet.CreateRow(0); IFont font = workbook.CreateFont(); font.FontName = "Arial";//字體樣式 ICellStyle headerStyle2 = workbook.CreateCellStyle(); headerStyle2.VerticalAlignment = VerticalAlignment.Center; //垂直居中 headerStyle2.WrapText = true;//自動換行 font.FontHeightInPoints = 9;//字體 //填充表頭 for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { ICellStyle headerStyle = workbook.CreateCellStyle(); headerStyle.FillForegroundColor = IndexedColors.PaleBlue.Index;//首行填充顏色 headerStyle.FillPattern = FillPattern.SolidForeground; headerStyle.VerticalAlignment = VerticalAlignment.Center; //垂直居中 headerStyle.WrapText = true;//自動換行 headerStyle.BorderTop = BorderStyle.Thin;//上邊框 headerStyle.BorderBottom = BorderStyle.Thin;//下邊框 headerStyle.BorderLeft = BorderStyle.Thin;//左邊框 headerStyle.BorderRight = BorderStyle.Thin;//右邊框 var cell = row.CreateCell(columnIndex); cell.CellStyle = headerStyle; cell.SetCellValue(dataTable.Columns[columnIndex].ColumnName.Replace("<br />", "\n")); //設置列名 row.HeightInPoints= 35; } //填充內容 for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++) { row = sheet.CreateRow(rowIndex + 1); for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { row.CreateCell(columnIndex).SetCellValue(Convert.ToString(dataTable.Rows[rowIndex][columnIndex])); ICell cellData = row.CreateCell(columnIndex); cellData.SetCellValue(dataTable.Rows[rowIndex][columnIndex].ToString().Replace("<br />", "\n")); cellData.CellStyle = headerStyle2; //把樣式賦給單元格 } } sheet.CreateFreezePane(0, 1, 0, 1); //首行凍結 workbook.Write(fs); //寫入到excel } } finally { if (workbook != null) workbook.Clear(); } }
        /// <summary>
        /// 在DataTable中添加一序號列,編號從1依次遞增
        /// </summary>
        /// <param >DataTable</param>
        /// <returns></returns>
        public static DataTable AddSeriNumToDataTable(DataTable dt)
        {
            //需要返回的值
            DataTable dtNew;
            if (dt.Columns.IndexOf("序號") >= 0)
            {
                dtNew = dt;
            }
            else //添加一序號列,並且在第一列
            {
                int rowLength = dt.Rows.Count;
                int colLength = dt.Columns.Count;
                DataRow[] newRows = new DataRow[rowLength];
                dtNew = new DataTable();
                //在第一列添加“序號”列
                dtNew.Columns.Add("序號");
                for (int i = 0; i < colLength; i++)
                {
                    dtNew.Columns.Add(dt.Columns[i].ColumnName);
                    //復制dt中的數據
                    for (int j = 0; j < rowLength; j++)
                    {
                        if (newRows[j] == null)
                            newRows[j] = dtNew.NewRow();
                        //將其他數據填充到第二列之后,因為第一列為新增的序號列
                        newRows[j][i + 1] = dt.Rows[j][i];
                    }
                }
                foreach (DataRow row in newRows)
                {
                    dtNew.Rows.Add(row);
                }
            }
            //對序號列填充,從1遞增
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dtNew.Rows[i]["序號"] = i + 1;
            }
            return dtNew;
        }
     /// <summary>
        /// Datatable導出Excel(無任何樣式)
        /// </summary>
        /// <param >DataTable</param>
        /// <returns></returns>
        public static void ExportExcel(DataTable dataTable, string filePath, string documentname)
        {
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                HSSFWorkbook excelBook = new HSSFWorkbook();
                ISheet sheet1 = excelBook.CreateSheet("Export Data");
                IRow row1 = sheet1.CreateRow(0);

                //填充表頭
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    row1.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
                }

                //填充內容
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    IRow rowTemp = sheet1.CreateRow(i + 1);
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        rowTemp.CreateCell(j).SetCellValue(string.Format("{0}", dataTable.Rows[i][j]));
                    }
                }
                //保存
                MemoryStream ms = new MemoryStream();
                excelBook.Write(ms);
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }
                string filedocmentname = "\\List.xls";
using (FileStream fs = new FileStream(filePath + filedocmentname, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } ms.Close(); ms.Dispose(); } }

縱向導出Excel效果圖

橫向導出Excel效果圖

版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM