本文详细叙述一下如何在VS中导出Excel报表,不足之处,还望见谅。Excel报表的导出有两种方式,一种是使用自身电脑预装的office的Excel组件;另一种是是用Myxls。这里介绍Myxls,myxls是一个c#写的开源组件,可以用来生成具有很多表格且包含格式的excel文件。
(注:本文部分程序转载于另一篇博文,时间有点长,找不到链接了,但还是觉得很好用,就再分享一下)
MyXls组件的压缩包在网盘中,解压后即可。
链接:https://pan.baidu.com/s/1_0aXyjJcc47bAU55ZMPiLQ
提取码:ilz8
复制这段内容后打开百度网盘手机App,操作更方便哦
这里举一个非常简单的使用例子。
- 首先在VS中新建一个Windows窗体应用(.NET Framework)的新项目,在Form窗口设计中添加一个dataGridview与button控件。将dataGridview的控件的name改为view1,这就随你了。
- 连接数据库,添加数据源(这就省略了)。
- 在你的解决方案下引用中添加MyXls.SL2.dll文件。
- 将方法代码写入。首先添加using指令或程序集引用(using org.in2bits.MyXls;),其次将 xlsGridview();方法函数加入,可移植性比较好,基本不用修改。
(运行截图)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using org.in2bits.MyXls;
using System.Data.SqlClient;
namespace WindowsFormsApp26
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string connString = "Data Source=(local);Initial Catalog=TeachingManagement;Integrated Security=True";
SqlDataAdapter da = new SqlDataAdapter("select * from Student", connString);
DataSet ds = new DataSet();
da.Fill(ds, "Student");
DataTable dt = ds.Tables["Student"];
view1.DataSource = dt;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void xlsGridview(DataGridView table, string localFilePath)
{
XlsDocument xls = new XlsDocument();
int rowIndex = 1; //行
int colIndex = 0; //列
Worksheet sheet = xls.Workbook.Worksheets.Add("sheet");//状态栏标题名称
Cells cells = sheet.Cells;
for (int i = 0; i < table.ColumnCount; i++) //列数
{
colIndex++;
sheet.Cells.Add(1, colIndex, table.Columns[i].HeaderText);
}
foreach (DataGridViewRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
for (int i = 0; i < table.ColumnCount; i++)
{
colIndex++;
if (row.Cells[table.Columns[i].Name].Value != null)
{
Cell cell = cells.Add(rowIndex, colIndex, row.Cells[table.Columns[i].Name].Value.ToString());
}
}
}
string filename = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);
string filepath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
xls.FileName = filename;
xls.Save(filepath, true);
}
private void button1_Click(object sender, EventArgs e)
{
if (view1.Rows.Count > 0)
{
SaveFileDialog sf1 = new SaveFileDialog();
sf1.Filter = "Excel files (*.xls)|*.xls";
if (sf1.ShowDialog() == DialogResult.OK)
{
string localFilePath = sf1.FileName.ToString();
xlsGridview(view1, localFilePath);
}
}
else
{
MessageBox.Show("无数据");
}
}
}
}