先看一下手动发送邮件内容加入表格操作(下图所示),直接复制Excel内容,再粘贴到邮件内容中,就是这么便捷,如果我们想自动发送邮件,也实现同样的效果如果实现呢,在这里介绍2种方法:
一.读取Excel转为HTML
1.C#读取Excel转为HTML代码
/// <summary> /// 测试用拼接Html /// </summary> public void Test() { string Body = @"你好: 附件为【{FileName}】资料,请注意查收. {Table} {Data} ============================ 此为系统自动发送邮件,请勿回复 pcbren致力于PCB自动化研究 ============================ "; string FileName = "pcbren"; Body = Body.Replace("{FileName}", FileName); Body = Body.Replace("{Data}", DateTime.Now.ToString("yyyy-MM-dd")); Body = Body.Replace("\r\n", "<br>"); string table = ReadXLS(@"E:\AA\test.xls"); Body = Body.Replace("{Table}", table); Body = @" <html> <style> table,table tr th, table tr td { border:1px solid #0094ff; } table { min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;} </style> <body> {body} </body> </html> ".Replace("{body}", Body); ; } /// <summary> /// 读取Excel表格内容 /// </summary> /// <param name="xlsPath"></param> /// <returns></returns> public string ReadXLS(string xlsPath) { object missing = System.Reflection.Missing.Value; Excel.Application app = new Excel.Application(); app.Visible = false; app.UserControl = true; Excel.Workbook wb = app.Application.Workbooks.Open(xlsPath, missing, true, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); int rowsint = ws.UsedRange.Cells.Rows.Count; //自动发邮件 表格行数应该固定更好 int columnsint = ws.UsedRange.Cells.Columns.Count;//自动发邮件 表格列数应该固定更好 StringBuilder sbHtml = new StringBuilder(1000); sbHtml.AppendLine("<table>"); for (int x = 1; x <= rowsint; x++) { string trLine = " <tr>"; int columnsSum = 0; for (int y = 1; y <= columnsint; y++) { trLine += (x == 1) ? "\r\n <th>" : "\r\n <td>"; var tt = (Excel.Range)ws.Cells[x, y]; string CellValue = (tt.Value ?? "").ToString().Trim(); trLine += CellValue; trLine += (x == 1) ? "</th>" : "</td>"; if (!string.IsNullOrEmpty(CellValue)) columnsSum++; } trLine += "\r\n </tr>"; if (columnsSum > 0) sbHtml.AppendLine(trLine); } sbHtml.AppendLine("</table>"); return sbHtml.ToString(); }