Winform入门(六) 读取excel及csv文件
2020-08-12 本文已影响0人
熊爸天下_56c7
一. 读取excel文件
下面这种方法是按照操作数据库的方法来读取xls文件, 用sql语句查询sheet1中的内容并赋给dataGridView
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace readEXCEL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null; //每次打开清空内容
DataSet dataSet = getData();
if (dataSet != null)
{
DataTable dt = dataSet.Tables[0];
RemoveEmpty(dt);
dataGridView1.DataSource = dt;
}
}
public DataSet getData()
{
//打开文件
OpenFileDialog file = new OpenFileDialog();
//file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
file.Filter = "Excel文件 |*.xlsx;*.xls";
file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
file.Multiselect = false;
if (file.ShowDialog() == DialogResult.Cancel)
return null;
//判断文件后缀
var path = file.FileName;
textBox1.Text = path;
string fileSuffix = System.IO.Path.GetExtension(path);
if (string.IsNullOrEmpty(fileSuffix))
return null;
using (DataSet ds = new DataSet())
{
//判断Excel文件是2003版本还是2007版本
string connString = "";
if (fileSuffix == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//读取文件
string sql_select = " SELECT * FROM [Sheet1$]";
using (OleDbConnection conn = new OleDbConnection(connString))
using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))
{
conn.Open();
cmd.Fill(ds);
}
if (ds == null || ds.Tables.Count <= 0) return null;
return ds;
}
}
//这个函数主要是用于去除表格中的空行
protected void RemoveEmpty(DataTable dt)
{
List<DataRow> removelist = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool IsNull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
IsNull = false;
}
}
if (IsNull)
{
removelist.Add(dt.Rows[i]);
}
}
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
}
}
}
二. 读取CSV文件
读取CSV是使用文件流的方法进行的
using Eco.Persistence.Configuration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
//打开文件
OpenFileDialog file = new OpenFileDialog();
file.Multiselect = false;
if (file.ShowDialog() != DialogResult.Cancel)
{
//判断文件后缀
var path = file.FileName;
textBox1.Text = path;
string fileSuffix = System.IO.Path.GetExtension(path);
if (fileSuffix == ".csv")
{
ReadTest(path);
}
};
}
public class CsvRow : List<string>
{
public string LineText { get; set; }
}
/// <summary>
/// Class to write data to a CSV file
/// </summary>
public class CsvFileWriter : StreamWriter
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
/// <summary>
/// Writes a single row to a CSV file.
/// </summary>
/// <param name="row">The row to be written</param>
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
// Add separator if this isn't the first value
if (!firstColumn)
builder.Append(',');
// Implement special handling for values that contain comma or quote
// Enclose in quotes and double up any double quotes
if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
else
builder.Append(value);
firstColumn = false;
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
}
/// <summary>
/// Class to read data from a CSV file
/// </summary>
public class CsvFileReader : StreamReader
{
public CsvFileReader(Stream stream)
: base(stream)
{
}
public CsvFileReader(string filename)
: base(filename)
{
}
/// <summary>
/// Reads a row of data from a CSV file
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public bool ReadRow(CsvRow row)
{
row.LineText = ReadLine();
if (String.IsNullOrEmpty(row.LineText))
return false;
int pos = 0;
int rows = 0;
while (pos < row.LineText.Length)
{
string value;
// Special handling for quoted field
if (row.LineText[pos] == '"')
{
// Skip initial quote
pos++;
// Parse quoted value
int start = pos;
while (pos < row.LineText.Length)
{
// Test for quote character
if (row.LineText[pos] == '"')
{
// Found one
pos++;
// If two quotes together, keep one
// Otherwise, indicates end of value
if (pos >= row.LineText.Length || row.LineText[pos] != '"')
{
pos--;
break;
}
}
pos++;
}
value = row.LineText.Substring(start, pos - start);
value = value.Replace("\"\"", "\"");
}
else
{
// Parse unquoted value
int start = pos;
while (pos < row.LineText.Length && row.LineText[pos] != ',')
pos++;
value = row.LineText.Substring(start, pos - start);
}
// Add field to list
if (rows < row.Count)
row[rows] = value;
else
row.Add(value);
rows++;
// Eat up to and including next comma
while (pos < row.LineText.Length && row.LineText[pos] != ',')
pos++;
if (pos < row.LineText.Length)
pos++;
}
// Delete any unused items
while (row.Count > rows)
row.RemoveAt(rows);
// Return true if any columns read
return (row.Count > 0);
}
}
void WriteTest(string filepath)
{
// Write sample data to CSV file
using (CsvFileWriter writer = new CsvFileWriter(filepath))
{
for (int i = 0; i < 100; i++)
{
CsvRow row = new CsvRow();
for (int j = 0; j < 5; j++)
row.Add(String.Format("Column{0}", j));
writer.WriteRow(row);
}
}
}
void ReadTest(string filepath)
{
DataTable dt = new DataTable();
dt.Columns.Add("序号", typeof(String));
dt.Columns.Add("温度", typeof(String));
dt.Columns.Add("时间", typeof(String));
dt.Columns.Add("备注", typeof(String));
// Read sample data from CSV file
using (CsvFileReader reader = new CsvFileReader(filepath))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
DataRow dr = dt.NewRow();
for (int i = 0; i < row.Capacity; i++)
{
dr[i] = row[i];
Console.Write(row[i]);
Console.Write(" ");
}
Console.WriteLine();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
}
}
}