datagridview輸出到excel字串格式

  • 3116
  • 0
  • C#
  • 2013-09-25

datagridview輸出到excel字串格式


private void ExportExcel()
{
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
    saveFileDialog.FilterIndex = 0;
    saveFileDialog.RestoreDirectory = true;
    saveFileDialog.CreatePrompt = true;
    saveFileDialog.Title = "輸出excel文件";
    saveFileDialog.ShowDialog();
    if (saveFileDialog.FileName.IndexOf(":") < 0) return;
    Stream myStream;
    myStream = saveFileDialog.OpenFile();
    StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.Default);
    string columnTitle = "";
    try
    {                
        for (int i = 0; i < dataGridView1.ColumnCount; i++)
        {
            if (i > 0)
            {
                columnTitle += "\t";
            }
            columnTitle += dataGridView1.Columns[i].HeaderText;
        }
        sw.WriteLine(columnTitle);

        for (int j = 0; j < dataGridView1.Rows.Count; j++)
        {
            string columnValue = "";
            for (int k = 0; k < dataGridView1.Columns.Count; k++)
            {
                if (k > 0)
                {
                    columnValue += "\t";
                }
                columnValue +=dataGridView1.Rows[j].Cells[k].Value.ToString();
            }                    
            sw.WriteLine(columnValue);
        }
        sw.Close();
        myStream.Close();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
    finally
    {
        sw.Close();
        myStream.Close();
    }
}