参考:
Visual Studio 进行Excel相关开发,Microsoft.Office.Interop.Excel.dll库 https://www.cnblogs.com/arxive/p/5786241.html
说明:
Microsoft.Office.Interop.Excel.dll 在VS中已自带,不需要再在网上下载。 引用方法:引用--扩展集,VS已自带Excel的dll库。 路径参考如下:D:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Excel.dll)
导出到Excel的方法:---测试ok!
private void ExportExcel(DataTable dt) { if (null == dt || dt.Rows.Count <= 0) return;
string savePath = string.Empty; FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择保存路径"; //dialog.RootFolder = Environment.SpecialFolder.Desktop; if (dialog.ShowDialog() == DialogResult.OK) { savePath = dialog.SelectedPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; } else { return; }
//需要添加 Microsoft.Office.Interop.Excel引用 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); if (null == app) { MessageBox.Show("缺少Excel组件!"); return; }
app.Visible = false; app.UserControl = true;
Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; worksheet.Name = "商品数据"; // 修改sheet名称 //Microsoft.Office.Interop.Excel.Range range; //long totalCount = dt.Rows.Count; //long rowRead = 0; //float percent = 0; // 导出进度
// 保存列名,Excel的索引从1开始 for (int i = 0; i < dt.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; // 标题设置 //range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; //range.Interior.ColorIndex = 15; // 背景色 //range.Font.Bold = true; // 粗体 } // 保存数据 for (int r = 0; r < dt.Rows.Count; r++) { for (int i = 0; i < dt.Columns.Count; i++) { worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString(); } //rowRead++; //percent = ((float)(100 * rowRead)) / totalCount; // 当前进度 }
// 合计: //worksheet.Cells[DT.Rows.Count + 2, 1] = "合计"; //worksheet.Cells[DT.Rows.Count + 2, 4] = DT.Compute("sum(Quantity)", ""); // DataTable筛选条件 //worksheet.Cells[DT.Rows.Count + 2, 6] = DT.Compute("sum(TotalAmt)", "");
//调整Excel的样式。 //Microsoft.Office.Interop.Excel.Range rg = worksheet.Cells.get_Range("A3", worksheet.Cells[rowCount + 2, 32]); //rg.Borders.LineStyle = 1; //单元格加边框 //worksheet.Columns.AutoFit(); //自动调整列宽
//隐藏某一行 //选中部分单元格,把选中的单元格所在的行的Hidden属性设为true //worksheet.get_Range(app.Cells[2, 1], app.Cells[2, 32]).EntireRow.Hidden = true;
//删除某一行 // worksheet.get_Range(app.Cells[2, 1], app.Cells[2, 32]).EntireRow.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
//string savePath = "导出数据.xls"; //string savePath = System.Windows.Forms.Application.StartupPath + "\\"+DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
workbook.SaveAs(savePath);
// 释放资源 workbook.Close(); workbook = null; app.Quit(); app = null;
MessageBox.Show("导出数据成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
|
请发表评论