C#实现DataTable、DataSet导出Excel,Excel导入为DataTable、DataSet,图片导出至Excel

一、引入dll文件

要实现Excel导入导出,必须要引入必要的dll依赖:程序集 NPOI.dll, v2.2.1.0

话不多说,下面直接上各种代码实现。

二、代码实现

C# 图片导出至Excel,需要在导出文件至excel代码中加入对图片的读取,代码如下:

// 定义正则表达式用来匹配 img 标签   
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串   
MatchCollection matches = regImg.Matches(strValue);
if (matches.Count > 0)
{
    string imgUrl = matches[0].Groups["imgUrl"].Value;
    if (!string.IsNullOrEmpty(imgUrl))
    {
        try
        {
            string pro = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
            imgUrl = pro + imgUrl.Substring(2); 
            //读取文件
            FileStream pFileStream = new FileStream(imgUrl, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[pFileStream.Length];
            pFileStream.Read(bytes, 0, (int)pFileStream.Length);

            int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
            HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.CreateDrawingPatriarch();
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 70, 50, 21, 0, 23, 2);
            //处理照片位置,【图片左上角为(col, row)第row+1行col+1列,右下角为( col +1, row +1)第 col +1+1行row +1+1列,宽为100,高为50
            HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

以下是实现DataTable、DataSet导出Excel,Excel导入为DataTable、DataSet各种方法、各种参数下的方法。

1、由DataSet导出Excel

/// <summary>
/// 由DataSet导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <param name="fileName">指定Excel工作表名称</param>
/// <param name="sheetName">指定Excel工作表sheet页</param>
/// <returns>Excel工作表</returns>
public static void ExportDataSetToExcel(DataSet sourceDs, string fileName, string sheetName)
{
    MemoryStream ms = ExportDataSetToExcel(sourceDs, sheetName) as MemoryStream;
    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
    HttpContext.Current.Response.BinaryWrite(ms.ToArray());
    HttpContext.Current.Response.End();
    ms.Close();
    ms = null;
}

        /// <summary>
        /// 由DataSet导出Excel
        /// </summary>
        /// <param name="sourceTable">要导出数据的DataSet</param>
        /// <param name="sheetName">工作表sheet页</param>
        /// <returns>Excel工作表</returns>
        private static Stream ExportDataSetToExcel(DataSet sourceDs, string sheetName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            string[] sheetNames = sheetName.Split(',');
            for (int i = 0; i < sheetNames.Length; i++)
            {
                ISheet sheet = workbook.CreateSheet(sheetNames[i]);
                IRow headerRow = sheet.CreateRow(0);
                // handling header.
                foreach (DataColumn column in sourceDs.Tables[i].Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                // handling value.
                int rowIndex = 1;
                foreach (DataRow row in sourceDs.Tables[i].Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in sourceDs.Tables[i].Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }
                    rowIndex++;
                }
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            workbook = null;
            return ms;
        }

2、由DataTable导出Excel

        /// <summary>
        /// 由DataTable导出Excel
        /// </summary>
        /// <param name="sourceTable">要导出数据的DataTable</param>
        /// <param name="fileName">指定Excel工作表名称</param>
        /// <param name="sheetName">指定Excel工作表sheet页</param>
        /// <returns>Excel工作表</returns>
        public static void ExportDataTableToExcel(DataTable sourceTable, string fileName, string sheetName)
        {
            MemoryStream ms = ExportDataTableToExcel(sourceTable, sheetName) as MemoryStream;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            ms.Close();
            ms = null;
        }

        /// <summary>
        /// 由DataTable导出Excel
        /// </summary>
        /// <param name="sourceTable">要导出数据的DataTable</param>
        /// <param name="sheetName">指定Excel工作表sheet页</param>
        /// <returns>Excel工作表</returns>
        private static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();

            //head样式
            HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            IFont fontSubTitle = workbook.CreateFont();
            fontSubTitle.Boldweight = 800;//加粗
            headStyle.SetFont(fontSubTitle);

            //日期样式
            HSSFCellStyle DateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
            HSSFDataFormat DateFormat = (HSSFDataFormat)workbook.CreateDataFormat();
            DateStyle.DataFormat = DateFormat.GetFormat("yyyy-mm-dd hh:mm");

            MemoryStream ms = new MemoryStream();
            ISheet sheet = workbook.CreateSheet(sheetName);
            IRow headerRow = sheet.CreateRow(0);

            // handling header.
            foreach (DataColumn column in sourceTable.Columns)
            {
                HSSFCell headCell = (HSSFCell)headerRow.CreateCell(column.Ordinal);
                headCell.CellStyle = headStyle;
                headCell.SetCellValue(column.ColumnName);
            }
            int rowIndex = 1;
            foreach (DataRow row in sourceTable.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in sourceTable.Columns)
                {
                    string typeName = column.DataType.Name.ToLower();
                    Regex regNum = new Regex(@"^\d+(\.\d+)?$");
                    string cellValue = row[column].ToString().Trim();
                    //根据数据类型设置数据
                    if (typeName.IndexOf("int") > -1 || typeName.IndexOf("decimal") > -1 || typeName.IndexOf("double") > -1 || typeName.IndexOf("float") > -1 || typeName.IndexOf("money") > -1)
                    {
                        if (regNum.Match(cellValue).Success)
                            dataRow.CreateCell(column.Ordinal).SetCellValue(Convert.ToDouble(cellValue));
                        else
                            dataRow.CreateCell(column.Ordinal).SetCellValue(cellValue);
                    }
                    else if (typeName.IndexOf("date") > -1)
                    {
                        if (!string.IsNullOrEmpty(cellValue))
                        {
                            HSSFCell cell = (HSSFCell)dataRow.CreateCell(column.Ordinal);
                            cell.SetCellValue(Convert.ToDateTime(cellValue));
                            cell.CellStyle = DateStyle;
                        }
                        else
                            dataRow.CreateCell(column.Ordinal).SetCellValue(cellValue);
                    }
                    else if (typeName.IndexOf("bit") > -1)
                    {
                        if (!string.IsNullOrEmpty(cellValue))
                        {
                            cellValue = cellValue == "1" ? "是" : "否";
                        }
                        dataRow.CreateCell(column.Ordinal).SetCellValue(cellValue);
                    }
                    else
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(cellValue);
                    }
                }
                rowIndex++;
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            sheet = null;
            headerRow = null;
            workbook = null;
            return ms;
        }

3、html页面table导出excel

        /// <summary>
        /// html页面table导出excel
        /// </summary>
        /// <param name="sbTable"></param>
        /// <param name="fileName"></param>
        /// <param name="sheetName"></param>
        public static void HtmlTableToExcel(string sbTable, string fileName, string sheetName)
        {
            if (string.IsNullOrEmpty(sbTable)) { return; }

            //InitializeWorkbook();
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet1 = workbook.CreateSheet(sheetName);
            
            string rowContent = string.Empty;
            MatchCollection rowCollection = Regex.Matches(sbTable, @"<tr[^>]*>[\s\S]*?<\/tr>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对tr进行筛选

            NPOI.SS.UserModel.IFont fontSubTitle = workbook.CreateFont();
            fontSubTitle.Boldweight = 800;//加粗
            ICellStyle HeadCellStyle = workbook.CreateCellStyle();
            HeadCellStyle.SetFont(fontSubTitle);
            HeadCellStyle.BorderBottom = BorderStyle.Thin;
            HeadCellStyle.BorderLeft = BorderStyle.Thin;
            HeadCellStyle.BorderRight = BorderStyle.Thin;
            HeadCellStyle.BorderTop = BorderStyle.Thin;
            HeadCellStyle.Alignment = HorizontalAlignment.Center;
            HeadCellStyle.VerticalAlignment = VerticalAlignment.Center;

            NPOI.SS.UserModel.IFont fontBody = workbook.CreateFont();
            fontBody.Boldweight = 300;

            ICellStyle DataCellStyleText = workbook.CreateCellStyle();
            DataCellStyleText.SetFont(fontBody);
            DataCellStyleText.BorderBottom = BorderStyle.Thin;
            DataCellStyleText.BorderLeft = BorderStyle.Thin;
            DataCellStyleText.BorderRight = BorderStyle.Thin;
            DataCellStyleText.BorderTop = BorderStyle.Thin;
            DataCellStyleText.Alignment = HorizontalAlignment.Left;

            ICellStyle DataCellStyleNumber = workbook.CreateCellStyle();
            DataCellStyleNumber.SetFont(fontBody);
            DataCellStyleNumber.BorderBottom = BorderStyle.Thin;
            DataCellStyleNumber.BorderLeft = BorderStyle.Thin;
            DataCellStyleNumber.BorderRight = BorderStyle.Thin;
            DataCellStyleNumber.BorderTop = BorderStyle.Thin;
            DataCellStyleNumber.Alignment = HorizontalAlignment.Right;

            int totalCol = 0;

            Regex regNum = new Regex(@"^[-+]?\d+(\.\d+)?$");
            for (int i = 0; i < rowCollection.Count; i++)
            {
                HSSFRow row = (HSSFRow)sheet1.CreateRow(i);
                rowContent = rowCollection[i].Value;

                //计算总列数
                if (totalCol == 0)
                {
                    MatchCollection columnCollection1 = Regex.Matches(rowContent, @"<th[^>]*>[\s\S]*?<\/th>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对td进行筛选
                    for (int td = 0; td < columnCollection1.Count; td++)
                    {
                        int colSpan = 1;
                        string strValue = columnCollection1[td].Value;
                        string[] attrArray = strValue.ToLower().Substring(strValue.ToLower().IndexOf("<") + 1, strValue.ToLower().IndexOf(">") - 1).Split(' ');
                        foreach (string strKey in attrArray)
                        {
                            if (strKey.IndexOf("colspan") > -1)
                            {
                                string strColSpan = GetNumbers(strKey);
                                int.TryParse(GetNumbers(strColSpan), out colSpan);
                                break;
                            }
                        }
                        if (colSpan > 1)
                        {
                            totalCol += colSpan - 1;
                        }
                        totalCol++;
                    }
                }

                MatchCollection columnCollection = Regex.Matches(rowContent, @"<th[^>]*>[\s\S]*?<\/th>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对th进行筛选
                int nCol = 0;
                for (int td = 0; td < totalCol; td++)
                {
                    ICell headCell = row.CreateCell(td);
                    headCell.CellStyle = HeadCellStyle;
                    if (headCell.IsMergedCell || columnCollection.Count < 1)
                    {
                        continue;
                    }

                    string strValue = columnCollection[nCol].Value;

                    // 定义正则表达式用来匹配 img 标签   
                    Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
                    // 搜索匹配的字符串   
                    MatchCollection matches = regImg.Matches(strValue);
                    if (matches.Count > 0)
                    {
                        string imgUrl = matches[0].Groups["imgUrl"].Value;
                        if (!string.IsNullOrEmpty(imgUrl))
                        {
                            try
                            {
                                string pro = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
                                imgUrl = pro + imgUrl.Substring(2); 
                                //读取文件
                                FileStream pFileStream = new FileStream(imgUrl, FileMode.Open, FileAccess.Read);
                                byte[] bytes = new byte[pFileStream.Length];
                                pFileStream.Read(bytes, 0, (int)pFileStream.Length);

                                int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
                                HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.CreateDrawingPatriarch();
                                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 70, 50, 21, 0, 23, 2);
                                //处理照片位置,【图片左上角为(col, row)第row+1行col+1列,右下角为( col +1, row +1)第 col +1+1行row +1+1列,宽为100,高为50
                                HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                            }
                            catch (Exception ex)
                            {
                                LogHelper.WriteProgramLog(DateTime.Now + " 下载图片发生异常:"+ex.Message);
                            }
                        }
                    }

                    headCell.SetCellValue(StringFix.HtmlToTxt(strValue));

                    if (strValue.ToLower().IndexOf(">") > strValue.ToLower().IndexOf("<") + 3)
                    {
                        int rowSpan = 1;
                        int colSpan = 1;
                        string strRowSpan = "";
                        string strColSpan = "";
                        string[] attrArray = strValue.ToLower().Substring(strValue.ToLower().IndexOf("<") + 1, strValue.ToLower().IndexOf(">") - 1).Split(' ');
                        foreach (string strKey in attrArray)
                        {
                            if (strKey.IndexOf("rowspan") > -1)
                            {
                                strRowSpan = GetNumbers(strKey);
                                int.TryParse(GetNumbers(strRowSpan), out rowSpan);
                            }
                            if (strKey.IndexOf("colspan") > -1)
                            {
                                strColSpan = GetNumbers(strKey);
                                int.TryParse(GetNumbers(strColSpan), out colSpan);
                            }
                        }
                        if (rowSpan > 1 || colSpan > 1)
                        {
                            sheet1.AddMergedRegion(new CellRangeAddress(i, i + rowSpan - 1, td, td + colSpan - 1));
                            //td += colSpan - 1;
                        }
                    }
                    nCol++;
                }
                if (columnCollection.Count > 0)
                    continue;

                nCol = 0;
                columnCollection = Regex.Matches(rowContent, @"<td[^>]*>[\s\S]*?<\/td>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对td进行筛选
                for (int td = 0; td < totalCol; td++)
                {
                    ICell dataCell = row.CreateCell(td);
                    if (dataCell.IsMergedCell)
                    {
                        dataCell.CellStyle = DataCellStyleText;
                        continue;
                    }

                    //string strValue = columnCollection[td].Value;
                    string strValue = columnCollection[nCol].Value;
                    string cellValue = StringFix.HtmlToTxt(strValue).Trim();
                    string[] attrArray = StringFix.SplitMulti(strValue.ToLower().Substring(strValue.ToLower().IndexOf("<") + 1, strValue.ToLower().IndexOf(">") - 1).Replace("\"", "'").Replace(": ", ":"), " ");
                    bool bCellFmt = true;  //带格式为true,否则为false默认string
                    if (strValue.ToLower().IndexOf(">") > strValue.ToLower().IndexOf("<") + 3)
                    {
                        int rowSpan = 1;
                        int colSpan = 1;
                        string strRowSpan = "";
                        string strColSpan = "";
                        //string[] attrArray = strValue.ToLower().Substring(strValue.ToLower().IndexOf("<") + 1, strValue.ToLower().IndexOf(">") - 1).Split(" ".ToCharArray());
                        foreach (string strKey in attrArray)
                        {
                            if (strKey.IndexOf("rowspan") > -1)
                            {
                                strRowSpan = GetNumbers(strKey);
                                int.TryParse(GetNumbers(strRowSpan), out rowSpan);
                            }
                            if (strKey.IndexOf("colspan") > -1)
                            {
                                strColSpan = GetNumbers(strKey);
                                int.TryParse(GetNumbers(strColSpan), out colSpan);
                            }
                            if (strKey.IndexOf("cellfmt") > -1)
                            {
                                string strCell = strKey.Split('=')[1].Replace(",", "");
                                if (strCell.IndexOf("string") > -1)
                                    bCellFmt = false;
                            }
                        }
                        if (rowSpan > 1 || colSpan > 1)
                        {
                            CellRangeAddress mergeRegion = new CellRangeAddress(i, i + rowSpan - 1, td, td + colSpan - 1);
                            sheet1.AddMergedRegion(mergeRegion);
                            td += colSpan - 1;
                        }
                    }
                    if (regNum.Match(cellValue).Success && bCellFmt)
                    {
                        dataCell.SetCellValue(Convert.ToDouble(StringFix.HtmlToTxt(cellValue).Trim()));
                        dataCell.CellStyle = DataCellStyleNumber;
                    }
                    else
                    {
                        dataCell.SetCellValue(StringFix.HtmlToTxt(cellValue).Trim());
                        dataCell.CellStyle = DataCellStyleText;
                    }
                    nCol++;
                    if (nCol >= columnCollection.Count)
                    {
                        break;
                    }
                }
            }

            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            HttpContext.Current.Response.ContentType = "binary/octet-stream;";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName) + ".xls");
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            ms.Close();
            ms = null;
        }

        public static string GetNumbers(string p_str)
        {
            string strReturn = string.Empty;
            if (p_str == null || p_str.Trim() == "")
            {
                strReturn = "";
            }

            foreach (char chrTemp in p_str)
            {
                if (Char.IsNumber(chrTemp))
                {
                    strReturn += chrTemp.ToString();
                }
            }
            return strReturn;
        }

4、将Excel导出到DataTable里

        /// <summary>
        /// 将Excel导出到DataTable里
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static DataTable ImportDataTableFromExcel(string filePath)
        {
            DataTable dt = new DataTable();
            using (FileStream fsRead = System.IO.File.OpenRead(filePath))
            {
                IWorkbook wk = null;
                //获取后缀名
                string extension = filePath.Substring(filePath.LastIndexOf(".")).ToString().ToLower();
                //判断是否是excel文件
                if (extension == ".xlsx" || extension == ".xls")
                {
                    //判断excel的版本
                    if (extension == ".xlsx")  //07以上版本
                    {
                        wk = new XSSFWorkbook(fsRead);
                    }
                    else
                    {
                        wk = new HSSFWorkbook(fsRead);
                    }

                    //获取第一个sheet
                    ISheet sheet = wk.GetSheetAt(0);

                    //获取第一行,一般第一行做标题既字段
                    IRow headrow = sheet.GetRow(0);

                    //创建列
                    for (int i = headrow.FirstCellNum; i < headrow.Cells.Count; i++)
                    {
                        DataColumn datacolum = new DataColumn(headrow.Cells[i].StringCellValue);
                        dt.Columns.Add(datacolum);
                    }
                    //读取每行,从第二行起
                    for (int r = 1; r <= sheet.LastRowNum; r++)
                    {
                        //bool result = false;
                        DataRow dr = dt.NewRow();
                        //获取当前行
                        IRow row = sheet.GetRow(r);
                        if (row != null && row.Cells.Count > 0)
                        {
                            //读取每列
                            for (int j = 0; j < headrow.Cells.Count; j++)
                            //for (int j = 0; j < row.Cells.Count; j++)
                            {
                                ICell cell = row.GetCell(j); //一个单元格
                                dr[j] = GetCellValue(cell); //获取单元格的值

                                //全为空则不取
                                //if (dr[j] != null && !string.IsNullOrEmpty(dr[j].ToStrings()))
                                //{
                                //    result = true;
                                //}
                            }
                            //if (result == true)
                            //{
                            //    dt.Rows.Add(dr); //把每行追加到DataTable
                            //}

                            dt.Rows.Add(dr);
                        }
                    }
                }

            }
            return dt;
        }
        /// <summary>
        /// 单元格格式匹配
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank: //空数据类型 这里类型注意一下,不同版本NPOI大小写可能不一样,有的版本是Blank(首字母大写)
                    return string.Empty;
                case CellType.Boolean: //bool类型
                    return cell.BooleanCellValue.ToStrings();
                case CellType.Error:
                    return cell.ErrorCellValue.ToStrings();
                case CellType.Numeric: //数字类型
                    if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
                    {
                        return cell.DateCellValue.ToStrings();
                    }
                    else //其它数字
                    {
                        return cell.NumericCellValue.ToStrings();
                    }
                case CellType.Unknown: //无法识别类型
                    return cell.StringCellValue.ToStrings();
                case CellType.String: //string 类型
                    return cell.StringCellValue.ToStrings();
                case CellType.Formula: //带公式类型
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToStrings();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToStrings();
                    }
                default: //默认类型
                    return cell.ToStrings();//
            }
        }

5、根据sheetname将Excel导入DataTable

        /// <summary>
        /// 由Excel导入DataTable
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
        /// <param name="sheetName">Excel工作表名称</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataTable</returns>
        public static DataTable ImportDataTableFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
        {
            using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
            {
                return ImportDataTableFromExcel(stream, sheetName, headerRowIndex);
            }
        }

        /// <summary>
        /// 由Excel导入DataTable
        /// </summary>
        /// <param name="excelFileStream">Excel文件流</param>
        /// <param name="sheetName">Excel工作表名称</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataTable</returns>
        public static DataTable ImportDataTableFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
        {
            HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
            ISheet sheet = workbook.GetSheet(sheetName);
            DataTable table = new DataTable();
            IRow headerRow = sheet.GetRow(headerRowIndex);
            int cellCount = headerRow.LastCellNum;
            for (int i = headerRow.FirstCellNum; i < cellCount; i++)
            {
                DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }
            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = table.NewRow();
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (!string.IsNullOrEmpty(row.GetCell(j).ToStrings()))
                    {
                        dataRow[j] = row.GetCell(j).ToString();
                    }
                    else
                    {
                        dataRow[j] = "";
                    }
                }



            }
            excelFileStream.Close();
            workbook = null;
            sheet = null;
            return table;
        }

6、 根据sheet页将excel导入DataTable

        /// <summary>
        /// 由Excel导入DataTable
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
        /// <param name="sheetIndex">Excel工作表索引</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataTable</returns>
        public static DataTable ImportDataTableFromExcel(string excelFilePath, int sheetIndex, int headerRowIndex)
        {
            using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
            {
                return ImportDataTableFromExcel(stream, sheetIndex, headerRowIndex);
            }
        }

        /// <summary>
        /// 由Excel导入DataTable
        /// </summary>
        /// <param name="excelFileStream">Excel文件流</param>
        /// <param name="sheetIndex">Excel工作表索引</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataTable</returns>
        public static DataTable ImportDataTableFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
        {
            HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
            ISheet sheet = workbook.GetSheetAt(sheetIndex);
            DataTable table = new DataTable();
            IRow headerRow = sheet.GetRow(headerRowIndex);
            int cellCount = headerRow.LastCellNum;
            for (int i = headerRow.FirstCellNum; i < cellCount; i++)
            {
                if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
                {
                    // 如果遇到第一个空列,则不再继续向后读取
                    cellCount = i + 1;
                    break;
                }
                DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }
            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                //if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "")
                //{
                //    // 如果遇到第一个空行,则不再继续向后读取
                //    break;
                //}
                DataRow dataRow = table.NewRow();
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    dataRow[j] = row.GetCell(j);
                }
                table.Rows.Add(dataRow);
            }
            excelFileStream.Close();
            workbook = null;
            sheet = null;
            return table;
        }

 7、由Excel导入DataSet,如果有多个工作表,则导入多个DataTable

        /// <summary>
        /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataSet</returns>
        public static DataSet ImportDataSetFromExcel(string excelFilePath, int headerRowIndex)
        {
            using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
            {
                return ImportDataSetFromExcel(stream, headerRowIndex);
            }
        }

        /// <summary>
        /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable
        /// </summary>
        /// <param name="excelFileStream">Excel文件流</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataSet</returns>
        public static DataSet ImportDataSetFromExcel(Stream excelFileStream, int headerRowIndex)
        {
            DataSet ds = new DataSet();
            HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
            for (int a = 0, b = workbook.NumberOfSheets; a < b; a++)
            {
                ISheet sheet = workbook.GetSheetAt(a);
                DataTable table = new DataTable();
                IRow headerRow = sheet.GetRow(headerRowIndex);
                int cellCount = headerRow.LastCellNum;
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
                    {
                        // 如果遇到第一个空列,则不再继续向后读取
                        cellCount = i + 1;
                        break;
                    }
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    table.Columns.Add(column);
                }
                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "")
                    {
                        // 如果遇到第一个空行,则不再继续向后读取
                        break;
                    }
                    DataRow dataRow = table.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            dataRow[j] = row.GetCell(j).ToString();
                        }
                    }
                    table.Rows.Add(dataRow);
                }
                ds.Tables.Add(table);
            }
            excelFileStream.Close();
            workbook = null;
            return ds;
        }

 

原创文章 79 获赞 56 访问量 17万+

猜你喜欢

转载自blog.csdn.net/qq_23009105/article/details/90613245