您的位置:首页 > 其它

DataGridView中的数据导入Excel

2008-07-25 01:04 399 查看
//保存的Excel
public bool SaveExcel(DataGridView girdView, bool isShowExcle)
{
if (girdView.Rows.Count == 0)  //判断数据是否等于0
return false;

//创建 Excel 对象
Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;

//生成字段名称(列名)
for (int i = 0; i < dataGridView1.ColumnCount - 1; i++)
{
excel.Cells[1, i + 1] = girdView.Columns[i].HeaderText;
}

//填充数据
for (int i = 0; i < girdView.RowCount - 1; i++)
{
for (int j = 0; j < girdView.ColumnCount; j++)
{
//判断类型是否是字符串
if (girdView[j, i].ValueType == typeof(string))
excel.Cells[i + 2, j + 1] = "'" + girdView[j, i].Value.ToString();
else
excel.Cells[i + 2, j + 1] = girdView[j, i].Value;
}
}
return true;
}[code]完善上一种方式:

public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";

saveFileDialog.ShowDialog();

Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
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";
}
if (dataGridview1.Rows[j].Cells[k].Value != null)
{
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();
}
}
[/code]
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: