把Excel读取到DataTable中,把DataTable输出为Excel

默认保存在输出目录下创建result+当前时间为文件名的Excel 2003(.xls)文件

ExcelToDataTable方法参数sheetName指定sheet,null表示取第一个sheet;isFirstRowColumn表示是否第一列是列名,true表示第一行是列名。

DataToExcel方法中可添加输出Excel文件的样式代码,此处为最朴素表格,不深究。

 

class ExcelUtil
    {
        private IWorkbook workbook = null;
        private FileStream fs = null;

        public DataTable ExcelToDataTable(string filePath, string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        public void DataToExcel(string path, DataTable data)
        {
            try
            {
                workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();

                //填充表头   
                IRow dataRow = sheet.CreateRow(0);
                foreach (DataColumn column in data.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                }

                //填充内容   
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    dataRow = sheet.CreateRow(i + 1);
                    for (int j = 0; j < data.Columns.Count; j++)
                    {
                        dataRow.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                }
                if (!path.EndsWith("\\"))
                {
                    path += "\\";
                }

                string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                string strFile = path + "\\result_" + time + ".xls";
                //保存   
                fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
                workbook.Write(fs);
                fs.Close();
                workbook.Close();
                MessageBox.Show("Finished!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

    }
}