private void ExportToExcel()
{
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 == “”)
{
return;
}
Stream 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 (dataGridView1.Columns[i].Visible == false || dataGridView1.Columns[i].DataPropertyName == “”)
{
continue;
}
str += dataGridView1.Columns[i].HeaderText;
str += “\t”;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
{
string strTemp = “”;
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (dataGridView1.Columns[k].Visible == false || dataGridView1.Columns[k].DataPropertyName == “”)
{
continue;
}
object obj = dataGridView1.Rows[j].Cells[k].Value;
if (obj != null)
{
strTemp += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
else
{
strTemp = “”;
}
strTemp += “\t”;
}
sw.WriteLine(strTemp);
}
sw.Close();
myStream.Close();
MessageBox.Show(“成功导出到Excel文件:\n” + saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
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("导出成功");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}