如何将文本转换为DataGridView中的列?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将文本转换为DataGridView中的列?相关的知识,希望对你有一定的参考价值。
我刚刚开始学习C#,我有这个问题...如何将文本转换为Excel中的DataGridView中的列?
来源格式:
NO BRAND NAME,ADRESS,PHONE
1 Brand1 Name1,address1,phone1
2 Brand2 Name2,address1,phone2
3 Brand1 Name3,address3,phone3
4 Brand3 Name4,address4,phone4
5 Brand1 Name5,address5,phone5
6 Brand1 Name6,address6,phone6
7 Brand4 Name7,address7,phone7
8 Brand2 Name8,address8,phone8
9 Brand4 Name9,address9,phone9
10 Brand2 Name10,address10,phone10
Excel来源:https://www.easypaste.org/file/dmqoMGDW/export-sources.xls?lang=en
我希望导入后的表格看起来像这样:enter image description here
谢谢我帮忙...
这是我的代码:
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 ExceltoDGV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openfile1.FileName;
string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties="Excel 8.0;HDR= yes;";";
OleDbConnection conn = new OleDbConnection(pathconn);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [Inwestycje$]", conn);
DataTable dt = new DataTable();
MyDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch
{
}
}
}
}
答案
我使用这种方法将我的csv转换为数据集。试试这个:
private DataTable GetDataFromSource(string connectionstring)
{
DataTable DtCsv = new DataTable();
string Fulltext;
using (StreamReader sr = new StreamReader(connectionstring))
{
while (!sr.EndOfStream)
{
Fulltext = sr.ReadToEnd().ToString(); //read full file text
string[] rows = Fulltext.Split('
'); //split full file text into rows
for (int i = 0; i < rows.Count() - 1; i++)
{
string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values
{
if (i == 0)
{
for (int j = 0; j < rowValues.Count(); j++)
{
DtCsv.Columns.Add(rowValues[j]); //add headers
}
}
else
{
DataRow dr = DtCsv.NewRow();
for (int k = 0; k < rowValues.Count(); k++)
{
dr[k] = rowValues[k].ToString();
}
DtCsv.Rows.Add(dr); //add other rows
}
}
}
}
}
return DtCsv;
}
以上是关于如何将文本转换为DataGridView中的列?的主要内容,如果未能解决你的问题,请参考以下文章