c# 读取Csv 读取xlsx 报错 DataTable, List<string>

读取Var 文件 转List<string>

  /// <summary>
        /// 读取Var 文件 
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="designPath"></param>
        /// <param name="speedPath"></param>
        /// <param name="mdList"></param>
        /// <param name="NotEqNumRatioValue"></param>
        /// <returns></returns>
        public List<string> openCsv(string fileVarName)
        {

            List<string> fileVar = null;
            #region  获取csv文件数据
            try
            {
                FileStream lFileStream = null;// openWaveFile(mFile);
                                              // lFileStream = mWaveUtilityClass.openWaveFile(fileName, out WaveVersion);
                lFileStream = new FileStream(fileVarName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (lFileStream == null)
                {
                    throw new Exception("wave文件数据读取错误");
                }
                System.Data.DataTable dataTable = new System.Data.DataTable();
                // List<SpanData> sds = new List<SpanData>();
                StreamReader sr = new StreamReader(lFileStream, System.Text.Encoding.GetEncoding("gb2312"));
                //string[] arrCDIData = new string[10] { "公里标", "速度", "空气动力补偿接触力", "支柱", "网压", "非接触导高1", "非接触导高2", "非接触拉出值1", "非接触拉出值2", "火花时间" };
                //int[] arrCDIIndex = new int[10];
                string s; int lineNum = 0; int outDataNum = 0;
                fileVar = new List<string>();

                while ((s = sr.ReadLine()) != null)
                {
                    try
                    {
                        if (lineNum == 0)
                        {
                            lineNum++;
                            continue;
                        }
                        string[] arrDataValue = s.Replace(" ", "").Split(',');
                        string txtData = string.Empty;
                        txtData += arrDataValue[0] + ",";   //序号
                        txtData += arrDataValue[1] + ",";   //公里标
                        txtData += arrDataValue[2] + ",";   //速度
                                                            //  txtData += arrDataValue[3] + ",";   //支柱标记
                        if (arrDataValue[11] == "1")//支柱标记 是1000 单元分界未必是1 ,支柱标记 是1000 单元分界未必是1  ——2021/10/12 LH 王斌提出通用文件修改
                        {//lh修改2021-10-11
                            txtData += "1000,";
                        }
                        else
                        {
                            txtData += arrDataValue[3] + ",";   //支柱标记
                        }
                        txtData += arrDataValue[4] + ",";   //弓网接触力
                        txtData += arrDataValue[5] + ",";   //网压
                        txtData += arrDataValue[6] + ",";   //接触线高度1
                        txtData += arrDataValue[7] + ",";   //接触线高度2
                        txtData += arrDataValue[8] + ",";   //接触线拉出值1
                        txtData += arrDataValue[9] + ",";   //接触线拉出值2
                        txtData += arrDataValue[10] + ",";  //火花时间(ms)
                                                            //txtData += arrDataValue[11];  //是否单元分界
                                                            //如果单元分界是1 但是支柱标记不是1000 把单元分界得1 修改为0;  ——2021/10/12 LH 王斌提出通用文件修改
                        if (arrDataValue[11].Equals("1") && !arrDataValue[3].Equals("1000"))
                        {//lh修改2021-10-11
                            txtData += "0";
                        }
                        else
                        {
                            txtData += arrDataValue[11];  //是否单元分界
                        }
                        fileVar.Add(txtData);
                        outDataNum++;
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("获取csv文件数据解析错误!");
            }
            #endregion



            return fileVar;
        }

读取Var 文件和 Xlsx通用文件 数据

 /// <summary>
        /// 读取Var 文件和 Xlsx通用文件 数据
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="designPath"></param>
        /// <param name="speedPath"></param>
        /// <param name="mdList"></param>
        /// <param name="NotEqNumRatioValue"></param>
        /// <returns></returns>
        public System.Data.DataTable ExcelToDataTable(string filePath, bool isColumnName, int sheetNum)
        {
            System.Data.DataTable dataTable = new System.Data.DataTable(); ;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本  
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本  
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);
                  
                    if (workbook != null)
                    {
                        sheet = workbook.GetSheetAt(sheetNum);//读取第一个sheet,当然也可以循环读取每个sheet  
                        dataTable = new System.Data.DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数  
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行  
                                int cellCount = firstRow.LastCellNum;//列数  

                                //构建datatable的列  
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名,则从第二行开始读取  
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("column" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }

                                //填充行  
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);
                                        if (cell == null)
                                        {
                                            dataRow[j] = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    dataRow[j] = "";
                                                    break;
                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理  
                                                    if (format == 14 || format == 31 || format == 57 || format == 58)
                                                        dataRow[j] = cell.DateCellValue;
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;
                                                case CellType.String:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                        }
                    }
                    fs.Close();
                }
                return dataTable;
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }
      

将CSV文件的数据读取到DataTable中

  /// <summary>
        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        public  DataTable OpenCSV(string filePath)
        {
            try
            {
                FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
               // Encoding encoding = GetEncoding(filePath); //Encoding.ASCII;//
                DataTable dt = new DataTable();

                StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("gb2312"));
                //string fileContent = sr.ReadToEnd();
                //encoding = sr.CurrentEncoding;
                //记录每次读取的一行记录
                string strLine = "";
                //记录每行记录中的各字段内容
                string[] aryLine = null;
                string[] tableHead = null;
                //标示列数
                int columnCount = 0;
                //标示是否是读取的第一行
                bool IsFirst = true;
                //逐行读取CSV中的数据
                while ((strLine = sr.ReadLine()) != null)
                {
                    if (IsFirst == true)
                    {
                        tableHead = strLine.Split(',');
                        IsFirst = false;
                        columnCount = tableHead.Length;//根据文件第一行,确定文件的列数
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {
                            DataColumn dc = new DataColumn(tableHead[i]);
                            dt.Columns.Add(dc);
                        }
                    }
                    else
                    {
                        aryLine = strLine.Split(',');
                        DataRow dr = dt.NewRow();
                        for (int j = 0; j < columnCount; j++)
                        {
                            dr[j] = aryLine[j];
                        }
                        dt.Rows.Add(dr);
                    }
                }
                if (aryLine != null && aryLine.Length > 0)
                {
                    dt.DefaultView.Sort = tableHead[0] + " " + "asc";
                }

                sr.Close();
                fs.Close();
                return dt;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(" 读取csv文件出错\r\n" + ex.Message);
                return null;
            }

        }

所用Dll

NPOI.rarNPOIC#调用导出xlsx文件-C#文档类资源-CSDN下载NPOIC#调用导出xlsx文件更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/qq_36074218/23475977?spm=1001.2014.3001.5503

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
inventoryButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (isFastClick()) { showLoadToast(); goToMainActivity(); loadExcelFile(); } } private boolean isFastClick() { return ButtonOnCilk.isFastViewClick(inventoryButton, getBaseContext()); } private void showLoadToast() { CustomToast.showLoad(HomeActivity.this, getString(R.string.load)); } private void goToMainActivity() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } private void loadExcelFile() { new AsyncTask<Void, Void, List<String>>() { @Override protected List<String> doInBackground(Void... voids) { return readExcelFile(); } @Override protected void onPostExecute(List<String> data) { showDataInListView(data); } }.execute(); } private void showDataInListView(List<String> data) { listView = findViewById(R.id.rv_list); if (listView != null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(HomeActivity.this, android.R.layout.simple_list_item_1, data); listView.setAdapter(adapter); } } });private List<String> readExcelFile() { List<String> datas = new ArrayList<>(); try { FileInputStream inputStream = new FileInputStream("/sdcard/Template/IC1001.xlsx"); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { datas.add(cell.toString()); } } workbook.close(); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } return datas; }报错List<List<String>>�޷�ת��ΪList<String> return readExcelFile();
最新发布
05-24

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值