• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#关于Excel文件转DataTable、转TXT文本的实现

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C#关于 Excel文件转DataTable、转TXT文本的实现

FileToDataTable

 /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName">文件的路径Path+FileName</param>
        /// <param name="sheetName">页签名</param>
        /// <returns></returns>
        private DataTable FileToDataTable(string fileName, string sheetName)
        {
            DataSet dst = new DataSet();
            DataTable dt = new DataTable();

            dt = XlsToDataTable(fileName, sheetName);

            return dt;
        }

XlsToDataTable

需要引用NPOL.dll

  public DataTable XlsToDataTable(string vFilePath, string vSheetName)
        {
            DataTable dataTable = new DataTable();
            Stream stream = null;
            try
            {
                stream = File.OpenRead(vFilePath);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(stream);
                HSSFSheet hssfsheet = (HSSFSheet)hssfworkbook.GetSheet(vSheetName);
                HSSFRow hssfrow = (HSSFRow)hssfsheet.GetRow(0);
                int lastCellNum = (int)hssfrow.LastCellNum;
                for (int i = (int)hssfrow.FirstCellNum; i < lastCellNum; i++)
                {
                    DataColumn column = new DataColumn(hssfrow.GetCell(i).StringCellValue);
                    dataTable.Columns.Add(column);
                }
                dataTable.TableName = vSheetName;
                int lastRowNum = hssfsheet.LastRowNum;
                for (int i = hssfsheet.FirstRowNum + 1; i <= hssfsheet.LastRowNum; i++)
                {
                    HSSFRow hssfrow2 = (HSSFRow)hssfsheet.GetRow(i);
                    DataRow dataRow = dataTable.NewRow();
                    for (int j = (int)hssfrow2.FirstCellNum; j < lastCellNum; j++)
                    {
                        dataRow[j] = hssfrow2.GetCell(j).ToString();
                    }
                    dataTable.Rows.Add(dataRow);
                }
                stream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Xls to DataTable: \n" + ex.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return dataTable;
        }

另外一种方法:

/*
     *引用 NuGet包 Spire.XLS
     */
    /// <summary>
    /// Excel帮助类
    /// </summary>
    public class ExcelHelper
    {
        /// <summary>
        /// 将Excel以文件流转换DataTable
        /// </summary>
        /// <param name="hasTitle">是否有表头</param>
        /// <param name="path">文件路径</param>
        /// <param name="tableindex">文件簿索引</param>
        public DataTable ExcelToDataTableFormPath(bool hasTitle = true, string path = "", int tableindex = 0)
        {
            //新建Workbook
            Workbook workbook = new Workbook();
            //将当前路径下的文件内容读取到workbook对象里面
            workbook.LoadFromFile(path);
            //得到第一个Sheet页
            Worksheet sheet = workbook.Worksheets[tableindex];
            return SheetToDataTable(hasTitle, sheet);
        }
        /// <summary>
        /// 将Excel以文件流转换DataTable
        /// </summary>
        /// <param name="hasTitle">是否有表头</param>
        /// <param name="stream">文件流</param>
        /// <param name="tableindex">文件簿索引</param>
        public DataTable ExcelToDataTableFormStream(bool hasTitle = true, Stream stream = null, int tableindex = 0)
        {
            //新建Workbook
            Workbook workbook = new Workbook();
            //将文件流内容读取到workbook对象里面
            workbook.LoadFromStream(stream);
            //得到第一个Sheet页
            Worksheet sheet = workbook.Worksheets[tableindex];
            return SheetToDataTable(hasTitle, sheet);
        }

        private DataTable SheetToDataTable(bool hasTitle, Worksheet sheet)
        {
            int iRowCount = sheet.Rows.Length;
            int iColCount = sheet.Columns.Length;
            DataTable dt = new DataTable();
            //生成列头
            for (int i = 0; i < iColCount; i++)
            {
                var name = "column" + i;
                if (hasTitle)
                {
                    var txt = sheet.Range[1, i + 1].Text;
                    if (!string.IsNullOrEmpty(txt)) name = txt;
                }
                while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。
                dt.Columns.Add(new DataColumn(name, typeof(string)));
            }
            //生成行数据
            int rowIdx = hasTitle ? 2 : 1;
            for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
            {
                DataRow dr = dt.NewRow();
                for (int iCol = 1; iCol <= iColCount; iCol++)
                {
                    dr[iCol - 1] = sheet.Range[iRow, iCol].Text;
                }
                dt.Rows.Add(dr);
            }
            return RemoveEmpty(dt);
        }

        /// <summary>
        /// 去除空行
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataTable RemoveEmpty(DataTable dt)
        {
            List<DataRow> removelist = new List<DataRow>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                bool rowdataisnull = true;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                    {
                        rowdataisnull = false;
                    }
                }
                if (rowdataisnull)
                {
                    removelist.Add(dt.Rows[i]);
                }
            }
            for (int i = 0; i < removelist.Count; i++)
            {
                dt.Rows.Remove(removelist[i]);
            }
            return dt;
        }
    }

DataTableToTxt 

  public object DataTableToTxt(DataTable vContent, string vOutputFilePath)
        {
            object resObj;
            StringBuilder sTxtContent;

            try
            {
                if (File.Exists(vOutputFilePath))
                    File.Delete(vOutputFilePath);

                sTxtContent = new StringBuilder();

                //数据
                foreach (DataRow row in vContent.Rows)
                {
                    for (int i = 0; i < vContent.Columns.Count; i++)
                    {
                        sTxtContent.Append(row[i].ToString().Trim());
                        sTxtContent.Append(i == vContent.Columns.Count - 1 ? "\r\n" : "\t");
                    }
                }
                File.WriteAllText(vOutputFilePath, sTxtContent.ToString(), Encoding.Unicode);
                resObj = new object[] { 0, "OK" };
            }
            catch (Exception ex)
            {
                resObj = new object[] { 0, "OK" };
            }
            return resObj;
        }

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#三层ATM-4.ATM界面设计发布时间:2022-07-10
下一篇:
C#之使用NotifyIcon实现任务栏托盘菜单,图标闪烁效果及气泡提示 ...发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap