您的位置:首页 > 编程语言 > C#

C#datagridview根据某一属性不同导出多份excel

2018-01-26 21:38 344 查看
项目里要求实现导出excel的功能,而且要求根据资产种类的不同从选中的资产中导出多份电子表格。下面以某社区的人员信息表为例编写例程。



1.基本思路

该信息表中,根据不同职业会有不同的属性,如学号是学生特有的,现在需要根据职业不同将这些人员及其属性导入到不同的excel表格中。基本思路见流程图。



2.前期准备

在编写导出的程序前,需要先编写一个只读类以存放各职业的属性,这样做就规定死了各种职业的属性,如果需要更加灵活的话应该在数据库中单独列一张表用于存放这些属性。以下摘取该类的片段。(类名为AssetType)

public class AssetType
{
private string[] teacher = { "编号", "姓名", "教师号" };
private string[] student = { "编号", "姓名", "学号" };
private string[] labor = { "编号", "姓名", "工号" };
private string[] businessman = { "编号", "姓名", "商号" };
public string[] Teacher
{
get { return this.teacher; }
}
public string[] Student
{
get { return this.student; }
}
public string[] Labor
{
get { return this.labor; }
}
public string[] Businessman
{
get { return this.businessman; }
}
}


3.代码

//按下该按键进行导出
private void output_Click(object sender, EventArgs e)
{
string[] typeNum = assetSort(dataGridView1);
ToExel(dataGridView1,typeNum);
}
//统计所选列表中共有多少种不同的职业
public string[] assetSort(DataGridView view)
{
string[] sort={"0","0","0","0"};
int number = 1;
//为类型数组赋值
sort[0] = view[6,0].Value.ToString();
for (int i = 1; i < view.RowCount; i++)
{
for (int j = 0; j < number; j++)
{
if (view[6,i].Value.ToString() == sort[j])
break;
if (j == number - 1)
{
sort[number] = view[6,i].Value.ToString();
number++;
if (number == 4)
break;
}
}
if (number == 4)//职业总数为4
break;
}
return sort;
}
//导出电子表格
public  void ToExel(DataGridView view,string[] types)
{
int length = types.Length;
int pNum;
string[] Properties;
for (int i = 0; i < length; i++)
{
//为当前的类型取回该导出的属性
Properties = returnProperties(types[i]);
pNum = Properties.Length;
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
//生成字段名称
for (int lable = 0; lable < pNum; lable++)
{
excel.Cells[1, lable + 1] = Properties[lable];
}
//填充数据
for (int row = 0,k=0; row <= 9; row++)
{
//如果本行不属于该类型,则不导出
if (view[6, row].Value.ToString() != types[i])
continue;
for(int j=0;j<pNum;j++)
{
for (int column = 0; column < view.ColumnCount; column++)
{
if (view.Columns[column].HeaderText == Properties[j])
{
if (view[column, row].ValueType == typeof(string))
{
excel.Cells[k + 2, j + 1] = "'" + view[column, row].Value.ToString();
}
else
{
excel.Cells[k + 2, j + 1] = view[column, row].Value.ToString();
}

break;
}
}

}
k++;
}
}
}
//根据类型返回其属性
public string[] returnProperties(string type)
{
AssetType assetType = new AssetType();
string[] typeProperties;
//默认为教师
typeProperties = assetType.Teacher;
if (type == "学生")
typeProperties = assetType.Student;
if (type == "工人")
typeProperties = assetType.Labor;
if (type == "商人")
typeProperties = assetType.Businessman;
return typeProperties;
}


4.成果

最后成功的导出三份excel电子表格。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C#