1、添加引用 MyXls.SL2.dll
2、添加 using org.in2bits.MyXls;
3、方法
//根据 文件名 生成excel
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++;
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);
}
4、调用
private void button2_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("没有数据");
}
}