C#读取excel文件 博客分类: C# C#excelcsvxlsxNPOI
程序员文章站
2024-03-25 15:10:22
...
C#读取excel文件
最近在项目中应用到读取excel文件的功能,在此总结一下开发经验。
读取数据分为两种情况,一种是csv格式的文件,另一种是xlsx格式的文件。
首先需要注意的是:csv文件是以英文逗号间隔的文本文件,而xlsx是电子表格,包含文本、数值、公式和格式。
代码示例:
读取csv文件
public class StudentEntity { public String name; public String no; public String fileName; } public String ReadCsvFileToEntityList(string filePath, String fileName, List<StudentEntity> stuList) { LoadUtil util = new LoadUtil(); String result = "S"; int i = 0; try { String fileAllName = filePath + @"\" + fileName; using (StreamReader sr = new StreamReader(fileAllName, Encoding.Default)) { String line; // 构造解析器 SeperatorBasedParser parser = new SeperatorBasedParser(seperator: SeperatorType.COMMA); // 按行拆解数据文件 while (!String.IsNullOrEmpty(line = sr.ReadLine())) { //去掉文件头 if (line.Contains("学号")) { continue; } var entity = parser.ParseStringToEntity<StudentEntity>(line); String[] lineList = line.Split(',');//根据英文逗号分隔 entity.fileName = fileName;//文件名 entity.no = lineList[0];//学号 entity.name = lineList[1];//姓名 stuList.Add(entity); i++; } Console.WriteLine("Total lines: " + i.ToString()); FileLogger.log("LoadManager.ParseFileToEntityList Succeed! " + fileAllName); } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file " + fileName + " could not be read: " + ", error line: " + i.ToString()); Console.WriteLine(e.Message); FileLogger.log(e); return null; } return result; }
读取xlsx文件:
const string connectStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; public string ReadXlsxFileToEntityList(string filePath, String fileName, List<StudentEntity> stuList) { String fileAllName = filePath + "\\" + fileName; string result = "S"; FileInfo fileInfo = new FileInfo(fileAllName); try { DataTable sheetTable = GetSheetTable(fileAllName); //只需要取第一个Sheet的sheetName string sheetName = sheetTable.Rows[0][2].ToString(); //读取Excel内容,将excel中的内容存在list中 DataTable dataTable = GetDataTable(fileAllName, sheetName); result = GetFocList(dataTable, fileName, stuList); } catch (Exception e) { return "E_" + e.Message; } return result; } /// <summary> /// 根据文件名称和sheet读取文件内容 /// </summary> /// <param name="fileName"></param> /// <param name="sheetName"></param> /// <returns></returns> public DataTable GetDataTable(string fileName, string sheetName) { DataTable dataTable = new DataTable(); OleDbConnection dbConn = new OleDbConnection(string.Format(connectStr, fileName)); try { dbConn.Open(); OleDbCommand dbCmd = new OleDbCommand(); dbCmd.Connection = dbConn; dbCmd.CommandText = "select * from [" + sheetName + "] "; dbCmd.CommandType = CommandType.Text; OleDbDataAdapter dbApt = new OleDbDataAdapter(dbCmd); dbApt.Fill(dataTable); } finally { dbConn.Close(); } return dataTable; } /// <summary> /// 根据文件名称获取文件中所有的sheetname /// </summary> /// <param name="filePath"></param> /// <returns></returns> public DataTable GetSheetTable(string filePath) { OleDbCommand dbCmd = new OleDbCommand(); OleDbConnection dbConn = new OleDbConnection(string.Format(connectStr, filePath)); DataTable sheetTable = null; try { dbConn.Open(); //dbTable装载了所有的sheetneame sheetTable = dbConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); dbConn.Close(); } catch (Exception e) { throw new Exception(e.Message); } finally { dbConn.Close(); } return sheetTable; } /// <summary> /// 将dataTable转换为entityList /// </summary> /// <param name="dataTable"></param> /// <param name="fileName"></param> /// <returns></returns> public String GetFocList(DataTable dataTable, String fileName, List<StudentEntity> stuList) { var result = "S"; if (dataTable.Rows.Count > 0) { for (int i = 0; i < dataTable.Rows.Count; i++) { try { //不读取文件头 if (dataTable.Rows[i][0].ToString().Trim().Contains("学号")) { continue; } StudentEntity entity = new StudentEntity(); entity.fileName = fileName;//文件名 entity.no = dataTable.Rows[i][0].ToString().Trim();//学号 entity.name = dataTable.Rows[i][1].ToString().Trim();//姓名 stuList.Add(entity); } catch (Exception e) { throw new Exception(e.Message + " " + i + " " + dataTable.Rows[i]); } } } return result; }
上一篇: android4.0 使用百度地图不能自动刷新问题 博客分类: Android android百度地图刷新
下一篇: C# data_gridview 应用 博客分类: C#oracle数据库 c#data_gridview数据绑定导出excel
推荐阅读
-
C#读取excel文件 博客分类: C# C#excelcsvxlsxNPOI
-
NPOI生成excel表格 博客分类: C# NPOIEXCELC#表格
-
C# data_gridview 应用 博客分类: C#oracle数据库 c#data_gridview数据绑定导出excel
-
对文件和字符串压缩及解压缩类 博客分类: C#.Net c#压缩解压缩
-
C# 操作Excel命名区域(NamedRange):创建、更改、删除命名区域 博客分类: .NET Excel C#Spire.XLSexcel命名区域Excel API
-
C#中对文件夹及文件信息的操作 博客分类: net
-
ASP.NET(C#)读取Excel的文件内容
-
ASP.NET(C#)读取Excel的文件内容
-
使用VisioAutomation.vdx 导出 visio的vdx文件 博客分类: C# .NET接口+对接调试 visiovdxVisioAutomation绘制visio
-
从零开始构建MSBuild C#项目文件 博客分类: C# Msbuild自动化构建