在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
C# 读取Excel,其实有很多方法。但是今天要来一波华丽的操作。 先看效果: 以上这波操作使用了 ExcelDataReader 和 ExcelDataReader.DataSet 完成的。 ExcelDataReader 是一个快速读取 Excel 的 C# 库。使用简单,读取速度比较快,感觉比 NPOI 快一点。但是遗憾的是只能读 Excel 没有写的操作。 以上这波操作的全部代码: using ExcelDataReader; using System; using System.IO; using System.Windows.Forms; namespace ExcelFastRead { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "(Excel 97-03)|*.xls|(Excel 2007)|*.xlsx|ALL|*.*"; if (DialogResult.OK != dialog.ShowDialog()) { return; } string strFileName = dialog.FileName; if (string.IsNullOrWhiteSpace(strFileName)) { return; } using (var stream = File.Open(strFileName, FileMode.Open, FileAccess.Read)) { // Auto-detect format, supports: // - Binary Excel files (2.0-2003 format; *.xls) // - OpenXml Excel files (2007 format; *.xlsx) using (var reader = ExcelReaderFactory.CreateReader(stream)) { // Choose one of either 1 or 2: // 1. Use the reader methods do { while (reader.Read()) { // reader.GetDouble(0); } } while (reader.NextResult()); ExcelDataSetConfiguration configuration = new ExcelDataSetConfiguration() { // Gets or sets a value indicating whether to set the DataColumn.DataType // property in a second pass. //UseColumnDataType = true, // Gets or sets a callback to obtain configuration options for a DataTable. ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() { // Gets or sets a value indicating the prefix of generated column names. //EmptyColumnNamePrefix = "Column", // Gets or sets a value indicating whether to use a row from the // data as column names. UseHeaderRow = true, // Gets or sets a callback to determine which row is the header row. // Only called when UseHeaderRow = true. //ReadHeaderRow = (rowReader) => { // // F.ex skip the first row and use the 2nd row as column headers: // rowReader.Read(); //}, // Gets or sets a callback to determine whether to include the // current row in the DataTable. //FilterRow = (rowReader) => { // return true; //}, // Gets or sets a callback to determine whether to include the specific // column in the DataTable. Called once per column after reading the // headers. //FilterColumn = (rowReader, columnIndex) => { // return true; //} } }; var result = reader.AsDataSet(configuration); // 2. Use the AsDataSet extension method //var result = reader.AsDataSet(); dgvList.DataSource = result.Tables[0]; // The result of each spreadsheet is in result.Tables } } } } }
ExcelDataReader.DataSet nuget包管理
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论