我正在忙着开发一个能够管理收入的小应用程序。我进入datagridview(通过文本框)数据,它们将相互添加。
" export"按钮存在,它都应该导出到Excel。 W 母鸡我用一条线进行测试,它有效。只要我有多行,我就有权发出此错误:
对象引用未设置为对象的实例。
当我离开Visual Studio时,Excel窗口似乎知道我是否要保存我的工作簿......我这样做了,它只保留了一行,即使我创建了10行。
我受到了这段代码的启发,但很好.. https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff
这是我的代码
public partial class addVente : Form
{
public addVente()
{
InitializeComponent();
}
// Bouton valider le nouvel enregistrement
private void btnValider_Click_1(object sender, EventArgs e)
{
dataGridView1.Rows.Add(txtName.Text, txtProduit.Text, float.Parse(txtPa.Text), float.Parse(txtPv.Text), float.Parse(txtComm.Text));
}
// On crée un nouveau mois
private void btnNouveauMois_Click(object sender, EventArgs e)
{
DialogResult newMonth = MessageBox.Show("Feuille du mois bien sauvegardée?", "Commencer un nouveau mois", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (newMonth == DialogResult.Yes)
this.Close();
}
// Exporter vers Excel. Ne fonctionne pas correctemnet !!!!
private void ExportToExcel()
{
// Creating a Excel object.
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Enregistrement effectué !");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}
private void btnExport_Click(object sender, EventArgs e)
{
ExportToExcel();
}
private void btnOuvrir_Click(object sender, EventArgs e)
{
MessageBox.Show("en cours de développement");
}
}