/// <summary>
/// 将DataGridView中的数据导入到Excel中
/// </summary>
/// <param name="dt">DataGridView</param>
/// <param name="templatePath">模板的路径</param>
/// <param name="excelName">导入Excel的路径</param>
/// <returns></returns>
public static bool DataGridViewToExcel(DataGridView dg, string templatePath, string excelName)
{
bool result = true;
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(templatePath))
{
xmlDoc.Load(templatePath);
XmlNode root = xmlDoc.SelectSingleNode(@"/*[local-name()='Workbook']/*[local-name()='Worksheet'][1]/*[local-name()='Table']");
foreach (DataGridViewRow dgRow in dg.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 in dg.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);
#endregion
XmlNode 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;
}
return result;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)