[C#] 使用NPOI将Datatable保存到Excel

 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;
            }

 

转载于:https://www.cnblogs.com/linhuide/p/5942330.html

你可能感兴趣的:([C#] 使用NPOI将Datatable保存到Excel)