0
我目前正在從Excel表導入數據從Excel表到SQL Server.i已經寫了一個從Excel表中刪除空行的代碼..現在我想通過分配來查看datagridview中的數據方法名稱爲datagridview datasource ..但它不顯示任何數據。任何人都可以說我是否正確或錯誤。這是我的代碼..數據沒有顯示在datagridview
public partial class Form9 : Form
{
DataSet dsExcel = new DataSet();
public Form9()
{
InitializeComponent();
}
private void btnUpload_Click(object sender, EventArgs e)
{
//String input = string.Empty;
OpenFileDialog filepath = new OpenFileDialog();
filepath.Filter = "Excel Files(*.xls)|*.xls|Excel Files(*.xlsx)|*.xlsx|Text Files(*.txt)|*.txt|All Files(*.*)|*.*";
filepath.InitialDirectory = "C:";
filepath.Title = "Select a file";
if (filepath.ShowDialog() == DialogResult.OK)
txtExcelFile.Text = filepath.FileName;
if (txtExcelFile.Text == string.Empty)
return;
}
private void btnImport_Click(object sender, EventArgs e)
{
OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + txtExcelFile.Text + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'");
cnn.Open();
try
{
OleDbDataAdapter data = new OleDbDataAdapter("select * from [Customers$]", cnn);
data.Fill(dsExcel);
dgvCustomers.ColumnHeadersVisible = false;
dgvCustomers.DataSource = GetExcelData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//cnn.Close();
}
}
public DataSet GetExcelData()
{
DataTable ExcelTable = new DataTable();
List<int> rowToRemove = new List<int>();
//DataRow ExcelRow = new DataRow();
foreach (DataRow excelrow in dsExcel.Tables[0].Rows)
{
bool IsEmpty = false;
foreach (object item in excelrow.ItemArray)
{
if (String.IsNullOrEmpty(item.ToString()))
{
IsEmpty = true;
break;
}
else
{
IsEmpty = false;
}
}
if (IsEmpty)
{
rowToRemove.Add((dsExcel.Tables[0].Rows.IndexOf(excelrow)));
}
}
for (int i = rowToRemove.Count - 1; i >= 0; i--)
{
dsExcel.Tables[0].Rows.RemoveAt(rowToRemove[i]);
}
return dsExcel;
}
}
}
感謝它worked..but我有一個doubt..i中所看到的datagridview數據源是Dataset的一些例子。我想知道爲什麼我們在這裏分配數據表而不是數據集..我是新編碼。從頭開始。 – Nazima
@Nazima將數據集看作數據庫 - 它可以容納多個數據表。 – LarsTech