C#-Winform-DataGridView-CSV
C#-Winform-DataGridView-CSV
一、界面搭建
二、DataGridView基本属性
编辑列的选项中可以进行设计:
- ColumnType:设计列的类型
- DataGridViewTextBoxColumn:文本内容
- DataGridViewCheckBoxColumn:勾选框内容
- DataGridViewComboBoxColumn:下拉选框内容
- DataGridViewImageColumn:图片格式内容
- DataGridViewLinkColumn:链接
- Name
- HeaderText
基本属性:
-
只读属性设定:
datagridview.ReadOnly = True
-
行自动追加:
datagridview.AllowUserToAddRows = False
-
删除行允许:
datagridview.AllowUserToDeleteRows = False
-
行幅设置:
datagridview.AllowUserToResizeRows = False datagridview.ColumnHeadersHeightSizeMode =DataGridViewColumnHeadersHeightSizeMode.DisableResizing
-
行表示:
datagridview.RowHeadersVisible = False
-
行选择模式:
datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect
-
复数行选择:
datagridview.MultiSelect = True
-
选择状态解除:
datagridview.ClearSelection()
-
文字设置位置:
datagridview.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
-
选择后行的颜色:
datagridview.DefaultCellStyle.SelectionBackColor = Color.GreenYellow datagridview.DefaultCellStyle.SelectionForeColor = Color.Black
-
行幅自动调整:
datagridview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
三、DataGridView和CSV
3.1 初始化数据
//初始化数据
private void btnInitData_Click(object sender, EventArgs e)
{
string[] strID = new string[] {"1", "2", "3", "4", "5"};
string[] strName = new string[] {"赵一", "钱二", "孙三", "李四", "周五"};
string[] strAddress = new string[] {"黑龙江", "江苏", "西藏", "新疆", "内蒙古"};
string[] strPhone = new string[] { "86-451", "86-025 ", "0891", "0995", "0477" };
gridTestData.Rows.Add(5);
for (int i = 0; i < gridTestData.Rows.Count; i++)
{
gridTestData.Rows[i].Cells[0].Value = strID[i];
gridTestData.Rows[i].Cells[1].Value = strName[i];
gridTestData.Rows[i].Cells[2].Value = strAddress[i];
gridTestData.Rows[i].Cells[3].Value = strPhone[i];
}
}
3.2 导出为CSV文件
//保存数据到csv文件
private void btnSaveToCSV_Click(object sender, EventArgs e)
{
//实例化SaveFileDialog
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存为csv文件";
//打开SaveFileDialog控件
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//数据流变量
Stream myStream;
//返回SaveFileDialog控件,并将所选择的文件转化成流
myStream = saveFileDialog.OpenFile();
//将选择的文件流生成写入流
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < gridTestData.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += ",";
}
columnTitle += gridTestData.Columns[i].HeaderText;
}
//将内容写入文件流中
sw.WriteLine(columnTitle);
for (int j = 0; j < gridTestData.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < gridTestData.Columns.Count; k++)
{
if (k > 0)
{
columnValue += ",";
}
if (gridTestData.Rows[j].Cells[k].Value == null)
{
columnValue += "";
}
else if (gridTestData.Rows[j].Cells[k].Value.ToString().Contains(","))
{
//将单元个中的,转义成文本
columnValue += "\"" + gridTestData.Rows[j].Cells[k].Value.ToString().Trim() + "\"";
}
else
{
//横向跳格
columnValue += gridTestData.Rows[j].Cells[k].Value.ToString().Trim() + "\t";
}
}
//内容写入文件流中
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
MessageBox.Show("导出表格成功!");
}
catch (Exception)
{
MessageBox.Show("导出表格失败!");
}
finally
{
sw.Close();
myStream.Close();
}
}
else
{
MessageBox.Show("取消导出表格操作!");
}
}
3.3 导入CSV文件
- 定义csv文件的实体类:
public class CSVExample
{
public string id;
public string name;
public string address;
public string phone;
public static CSVExample FromCsv(string csvContent)
{
string[] values = csvContent.Split(',');
CSVExample example = new CSVExample();
example.id = values[0];
example.name = values[1];
example.address = values[2];
example.phone = values[3];
return example;
}
}
- 具体实现
//将csv文件转成list,并绑定到DataGridView组件上
private void btnCSVToGrid_Click(object sender, EventArgs e)
{
//实例化SaveFileDialog
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Execl files (*.csv)|*.csv";
openFileDialog.FilterIndex = 0;
openFileDialog.RestoreDirectory = true;
openFileDialog.Title = "打开的文件";
//打开SaveFileDialog控件
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string path = Path.GetFullPath(openFileDialog.FileName);
//MessageBox.Show(path);
List<CSVExample> values = File.ReadAllLines(path, System.Text.Encoding.GetEncoding(-0))
.Skip(1)
.Select(v => CSVExample.FromCsv(v))
.ToList();
//MessageBox.Show(values.Count.ToString());
gridTestWrite.Rows.Add(values.Count);
for (int i = 0; i < values.Count; i++)
{
gridTestWrite.Rows[i].Cells[0].Value = values[i].id + ".csv";
gridTestWrite.Rows[i].Cells[1].Value = values[i].name + ".csv";
gridTestWrite.Rows[i].Cells[2].Value = values[i].address + ".csv";
gridTestWrite.Rows[i].Cells[3].Value = values[i].phone + ".csv";
}
}
}