[英]C# save DataGridView after editing (overwrite Excel file that was imported)
我有一個小表格,其中有3個Buttons
( Browse
& updateExcel
和saveExcel
), ComboBox
( comboBox1
)和DataGridView
( dataGridView1
)
第一個按鈕使您可以選擇一個Excel文件,然后將該文件加載到DataGridView
:
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = @"C:\";
op.Title = "Browse Excel Files";
op.CheckFileExists = true;
op.CheckPathExists = true;
op.DefaultExt = "xls";
op.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
op.FilterIndex = 2;
op.RestoreDirectory = true;
op.ReadOnlyChecked = true;
op.ShowReadOnly = true;
if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (File.Exists(op.FileName))
{
string[] Arr = null;
Arr = op.FileName.Split('.');
if (Arr.Length > 0)
{
if (Arr[Arr.Length - 1] == "xls")
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
op.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
else if (Arr[Arr.Length - 1] == "xlsx")
{
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + op.FileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
}
}
FillData();
}
}
這也使用以下代碼:
public string sConnectionString;
private void FillData()
{
if (sConnectionString.Length > 0)
{
OleDbConnection cn = new OleDbConnection(sConnectionString);
{
cn.Open();
DataTable dt = new DataTable();
OleDbDataAdapter Adpt = new OleDbDataAdapter("select * from [sheet1$]", cn);
Adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
try { }
catch (Exception ex)
{
}
}
}
然后,從ComboBox
選擇一個值之后,可以通過單擊使用以下代碼的updateExcel
按鈕,根據需要使用該值更新DataGridView
:
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1[2, i].Value = ConsigneeCombo.Text;
}
}
然后,我要執行的操作是單擊“保存”按鈕( saveExcel
),並使用來保存加載的文件。 Are you sure you want to save?
Yes
或No
標准Windows對話框。
我嘗試使用SaveFileDialogue
( saveFileDialog1
)執行此操作:
private void saveExcel_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = @"C:\";
saveFileDialog1.Title = "Save Excel File";
saveFileDialog1.DefaultExt = "xls";
saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
fs.Close();
}
}
但這不起作用,因為嘗試將文件另存為新文件(具有新的標簽名等),並且實際上無法識別文件類型。
我通過使用以下代碼解決了這個問題:
private void saveExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = @"C:\";
sfd.Title = "Save Excel Files";
sfd.CheckPathExists = true;
sfd.DefaultExt = "xls";
sfd.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
sfd.FileName = "*.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
ToCsV(dataGridView1, sfd.FileName);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.