這里提供了兩種將DataGridView內(nèi)容導(dǎo)出到Excel文件的方法。
成都創(chuàng)新互聯(lián)公司一直秉承“誠信做人,踏實(shí)做事”的原則,不欺瞞客戶,是我們最起碼的底線! 以服務(wù)為基礎(chǔ),以質(zhì)量求生存,以技術(shù)求發(fā)展,成交一個(gè)客戶多一個(gè)朋友!為您提供成都網(wǎng)站建設(shè)、網(wǎng)站制作、成都網(wǎng)頁設(shè)計(jì)、微信平臺(tái)小程序開發(fā)、成都網(wǎng)站開發(fā)、成都網(wǎng)站制作、成都軟件開發(fā)、成都App制作是成都本地專業(yè)的網(wǎng)站建設(shè)和網(wǎng)站設(shè)計(jì)公司,等你一起來見證!
方法1:
///
/// 在沒有安裝Excel的情況下,將DataGridView數(shù)據(jù)導(dǎo)出到Excel
///
private void ExportToExcel()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "導(dǎo)出到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("成功導(dǎo)出到Excel文件:\n" + saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
方法2:
///
/// 將DataGrirdView數(shù)據(jù)導(dǎo)出到Excel
/// 需要引用Microsoft.Office.Interop.Excel.dll模塊
///
///
///
///
private bool DataGridviewShowToExcel(DataGridView dgv, bool bShowExcel)
{
if (dgv.Rows.Count == 0)
{
return false;
}
//建立Excel對(duì)象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = bShowExcel;
//生成字段名稱
int k = 0;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Columns[i].Visible == false || dataGridView1.Columns[i].DataPropertyName == "")
{
k++;
continue;
}
excel.Cells[1, i + 1 - k] = dgv.Columns[i].HeaderText;
}
//填充數(shù)據(jù)
for (int i = 0; i < dgv.RowCount; i++)
{
k = 0;
for (int j = 0; j < dgv.ColumnCount; j++)
{
if (dgv.Columns[j].Visible == false || dataGridView1.Columns[j].DataPropertyName == "")
{
k++;
continue;
}
excel.Cells[i + 2, j + 1 - k] = dgv[j, i].Value.ToString();
}
}
return true;
}