mercredi 21 janvier 2015

C#: save to .xls


Vote count:

0





public void SaveAs()
{
if(dataGridView1.ColumnCount>=2)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
saveFileDialog.ShowDialog();

Stream myStream;

myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
// MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}

}
else
MessageBox.Show("No data to save", "OK",


MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); }


When I open the saving window and I decide not to save DataGridView1 by clicking Cancel I have an error " Index was outside the bounds of the array." at myStream = saveFileDialog.OpenFile();


I don't know what's wrong in here.



asked 1 min ago







C#: save to .xls

Aucun commentaire:

Enregistrer un commentaire