1. 程式人生 > >NPOI元件實現EXCEL大資料的讀取和寫入

NPOI元件實現EXCEL大資料的讀取和寫入

      public bool DataToExcel(DataTable SourceDataTable )
        {
            if (SourceDataTable == null) return false;
            if (SourceDataTable.Rows.Count == 0) return false;

            MemoryStream ms = new MemoryStream();

            try
            {
                using (SourceDataTable)
                {
                    String hz = Path.GetExtension(ExcelName);
                    IWorkbook workbook;

                    if (hz.Equals(".xls")) //針對2003版本  
                        workbook = new HSSFWorkbook();
                    else
                        workbook = new XSSFWorkbook();

                    NPOI.SS.UserModel.IFont font = workbook.CreateFont();
                    font.FontHeightInPoints = 12;
                    font.FontName = "宋體";
                    ICellStyle cellStyle = workbook.CreateCellStyle();
                    cellStyle.SetFont(font);

                    ISheet sheet = workbook.CreateSheet();
                    IRow headerRow = sheet.CreateRow(0);

                    // handling header.
                    foreach (DataColumn column in SourceDataTable.Columns)
                    {
                        sheet.SetColumnWidth(column.Ordinal, 10 * 256);
                        sheet.SetDefaultColumnStyle(column.Ordinal, cellStyle);
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);
                    }

                    // handling value.
                    int rowIndex = 0;

                    foreach (DataRow row in SourceDataTable.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
                        dataRow.RowStyle = cellStyle;
                        foreach (DataColumn column in SourceDataTable.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }

                        rowIndex++;
                    }

                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }

                File.Delete(ExcelName);

                using (FileStream fs = new FileStream(ExcelName, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();

                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
        }