黑马程序员技术交流社区
标题:
关于如何将c#将Winform下DataGridView中内容导出到Excel
[打印本页]
作者:
什麽才是王道
时间:
2012-2-18 15:06
标题:
关于如何将c#将Winform下DataGridView中内容导出到Excel
本帖最后由 什麽才是王道 于 2012-2-18 15:07 编辑
关于如何将c#将Winform下DataGridView中内容导出到Excel
方法1 :
添加dll引用
右击选择你所在的项目的“引用”,选择“添加引用”。
弹出“添加引用”对话框。
选择“COM”选项卡。
选择“Microsoft Excel 12.0 Object Library”
1.jpg
(71.01 KB, 下载次数: 44)
下载附件
2012-2-18 15:03 上传
单击“确定”按钮。
说明:
如何发现导入的程序集不能正常工作,可能是由于office安装的缘故,请确保自定义安装office时,选择“.net可编程性支持”:
2.jpg
(89.38 KB, 下载次数: 39)
下载附件
2012-2-18 15:03 上传
代码:
public static bool ExportForDataGridview(DataGridView gridView, string fileName, bool isShowExcle)
{
//建立Excel对象
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
if (app == null)
{
return false;
}
app.Visible = isShowExcle;
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
if (worksheet == null)
{
return false;
}
string sLen = "";
//取得最后一列列名
char H = (char)(64 + gridView.ColumnCount / 26);
char L = (char)(64 + gridView.ColumnCount % 26);
if (gridView.ColumnCount < 26)
{
sLen = L.ToString();
}
else
{
sLen = H.ToString() + L.ToString();
}
//标题
string sTmp = sLen + "1";
Range ranCaption = worksheet.get_Range(sTmp, "A1");
string[] asCaption = new string[gridView.ColumnCount];
for (int i = 0; i < gridView.ColumnCount; i++)
{
asCaption
= gridView.Columns
.HeaderText;
}
ranCaption.Value2 = asCaption;
//数据
object[] obj = new object[gridView.Columns.Count];
for (int r = 0; r < gridView.RowCount - 1; r++)
{
for (int l = 0; l < gridView.Columns.Count; l++)
{
if (gridView[l, r].ValueType == typeof(DateTime))
{
obj[l] = gridView[l, r].Value.ToString();
}
else
{
obj[l] = gridView[l, r].Value;
}
}
string cell1 = sLen + ((int)(r + 2)).ToString();
string cell2 = "A" + ((int)(r + 2)).ToString();
Range ran = worksheet.get_Range(cell1, cell2);
ran.Value2 = obj;
}
//保存
workbook.SaveCopyAs(fileName);
workbook.Saved = true;
}
finally
{
//关闭
app.UserControl = false;
app.Quit();
}
return true;
}
方法2
用流保存成xls文件. 这种方法比较好,不用引用Excel组件. 下面是具体例子,可以参考
using System.IO;
using System.Text;
/// <summary>
/// 另存新档按钮
/// </summary>
private void SaveAs() //另存新档按钮 导出成Excel
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl 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 < dgvAgeWeekSex.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dgvAgeWeekSex.Columns
.HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dgvAgeWeekSex.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dgvAgeWeekSex.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();
}
}
C# WinForm下DataGridView导出Excel的实现
1.说明:导出的效率说不上很高,但至少是可以接收的.参考网上很多高效导出Excel的方法,实现到时能够实现的,导出速度也很快,不过缺陷在与不能很好的进行单元格的格式化,比如上图中的"拼音码"字段中的值"000000000012120",在导出后就显示"12120",挺郁闷的!o(∩_∩)o,废话不说了,进入正题.......
2.首先添加Excel引用
3.实现代码
/// <summary>
/// DataGridView导出Excel
/// </summary>
/// <param name="strCaption">Excel文件中的标题</param>
/// <param name="myDGV">DataGridView 控件</param>
/// <returns>0:成功;1ataGridView中无记录;2:Excel无法启动;9999:异常错误</returns>
private int ExportExcel(string strCaption, DataGridView myDGV)
{
int result = 9999;
// 列索引,行索引,总列数,总行数
int ColIndex = 0;
int RowIndex = 0;
int ColCount = myDGV.ColumnCount;
int RowCount = myDGV.RowCount;
if (myDGV.RowCount == 0)
{
result = 1;
}
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
result = 2;
}
try
{
// 创建Excel工作薄
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
// 设置标题
Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = strCaption;
xlApp.ActiveCell.Font.Size = 20;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
// 创建缓存数据
object[,] objData = new object[RowCount + 1, ColCount];
//获取列标题
foreach (DataGridViewColumn col in myDGV.Columns)
{
objData[RowIndex, ColIndex++] = col.HeaderText;
}
// 获取数据
for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
{
for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
{
if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)
|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓存时在该内容前加入" ";
{
objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
}
else
{
objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
}
}
System.Windows.Forms.Application.DoEvents();
}
// 写入Excel
range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);
range.Value2 = objData;
//保存
xlBook.Saved = true;
xlBook.SaveCopyAs("C:\\测试" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
//返回值
result = 0;
}
catch (Exception err)
{
result = 9999;
}
finally
{
xlApp.Quit();
GC.Collect(); //强制回收
}
return result;
}
4.调用方法(上图中"生成Excel文件"按钮的on
Click事件)
private void button4_Click(object sender, EventArgs e)
{
int result = this.ExportExcel("测试", this.dataGridView1); //this.dataGridView1ataGridView控件
MessageBox.Show(result.ToString());
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2