winform遍历bartender_RFID的winform程序心得1

///

///将DataGridView中的数据导入到Excel中///

/// DataGridView

/// 模板的路径

/// 导入Excel的路径

///

public static bool DataGridViewToExcel(DataGridView dg, string templatePath, stringexcelName)

{bool result = true;

XmlDocument xmlDoc= newXmlDocument();if(File.Exists(templatePath))

{

xmlDoc.Load(templatePath);

XmlNode root= xmlDoc.SelectSingleNode(@"/*[local-name()='Workbook']/*[local-name()='Worksheet'][1]/*[local-name()='Table']");foreach (DataGridViewRow dgRow indg.Rows)

{

XmlElement row= xmlDoc.CreateElement("", "Row", "urn:schemas-microsoft-com:office:spreadsheet");

row.SetAttribute("AutoFitHeight", "urn:schemas-microsoft-com:office:spreadsheet", "0");foreach (DataGridViewColumn dgcol indg.Columns)

{if (dgcol.Visible && dgcol.IsDataBound && dgcol.GetType().Name == "DataGridViewTextBoxColumn")

{

XmlElement cell= xmlDoc.CreateElement("", "Cell", "urn:schemas-microsoft-com:office:spreadsheet");

XmlElement data= xmlDoc.CreateElement("", "Data", "urn:schemas-microsoft-com:office:spreadsheet");

data.SetAttribute("Type", "urn:schemas-microsoft-com:office:spreadsheet", "String");

data.InnerText=StringUility.ReturnFormatString(dgRow.Cells[dgcol.Name].Value);

cell.AppendChild(data);

row.AppendChild(cell);

}

}//root.InsertBefore(row, root.LastChild);

root.AppendChild(row);

}#region 添加合计行XmlElement totalRow= xmlDoc.CreateElement("", "Row", "urn:schemas-microsoft-com:office:spreadsheet");

totalRow.SetAttribute("AutoFitHeight", "urn:schemas-microsoft-com:office:spreadsheet", "0");for (int i = 0; i < 2; i++)

{

XmlElement cell= xmlDoc.CreateElement("", "Cell", "urn:schemas-microsoft-com:office:spreadsheet");

XmlElement data= xmlDoc.CreateElement("", "Data", "urn:schemas-microsoft-com:office:spreadsheet");

data.SetAttribute("Type", "urn:schemas-microsoft-com:office:spreadsheet", i == 0 ? "String" : "Number");

data.InnerText=(i==0?"合计":dg.Rows.Count.ToString());

cell.AppendChild(data);

totalRow.AppendChild(cell);

}

root.AppendChild(totalRow);#endregionXmlNode countnode= xmlDoc.SelectSingleNode(@"/*[local-name()='Workbook']/*[local-name()='Worksheet'][1]/*[local-name()='Table']");

countnode.Attributes["ss:ExpandedRowCount"].Value = (Int32.Parse(countnode.Attributes["ss:ExpandedRowCount"].Value) + dg.Rows.Count+1).ToString();//标题+合计+数据

xmlDoc.Save(excelName);

result= true;

}else{

result= false;

}returnresult;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值