首页 > 技术文章 > [C#] 使用NPOI将Datatable保存到Excel

linhuide 2016-10-09 15:10 原文

 using (table)
            {
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);
                // handling header.  
                foreach (DataColumn column in table.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value  
                                                                                      // handling value.  
                int rowIndex = 1;
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in table.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());

                    }
                    rowIndex++;
                }

                workbook.Write(ms);
                FileStream file = new FileStream("E://原始动态.xls", FileMode.Create);
                workbook.Write(file);
                file.Close();
                workbook = null;
                ms.Flush();
                ms.Position = 0;
            }

 

推荐阅读