//打开保存对话框
public void show(string excelname,System.Data.DataTable dt)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "EXCEL表格(*.xlsx)|*.xlsx";
save.FileName = excelname;
//得到文件路径
string path = "";
//如果确定保存
if (save.ShowDialog() == DialogResult.OK)
{
path = save.FileName.ToString();
bool result = toexcel(excelname,dt, path);
//判断有没有导出成功
if (result)
{
MessageBox.Show("导出成功!");
}
else
{
MessageBox.Show("导出失败!");
}
}
else
{
return;
}
}
public bool toexcel(string excelname,System.Data.DataTable dt ,string path)
{
bool re = false;
if (dt.Rows.Count < 0)
{
MessageBox.Show("null");
}
else
{
//创建新的excel
Microsoft.Office.Interop.Excel.Application exApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exBook = exApp.Workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet exSheet = exBook.Worksheets[1];
string [] aaa = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count;i++ )
{
//exSheet.Cells[1][i+1] = dt.Columns[i].ColumnName.ToString();
aaa[i] = dt.Columns[i].ColumnName.ToString();
exSheet.Range[exSheet.Cells[1, 1], exSheet.Cells[1, dt.Columns.Count]].Value2 = aaa;
}
int rowNum = dt.Rows.Count;
int colNum = dt.Columns.Count;
string[,] finalData = new string[rowNum, colNum];
for (int i = 0; i < rowNum; i++)
{
for (int j = 0; j < colNum; j++)
{
finalData[i, j] = dt.Rows[i][j].ToString();
}
}
exSheet.Range[exSheet.Cells[2, 1], exSheet.Cells[rowNum + 1, colNum]].Value2 = finalData;
exSheet.Range[exSheet.Cells[2, 1], exSheet.Cells[rowNum + 1, colNum]].NumberFormatLocal = "@ ";
exBook.Saved = true;
exBook.SaveAs(path);
exBook.Close();
if(exApp != null)
{
exApp.Workbooks.Close();
exApp.Quit();
}
re = true;
}
return re;
}
.net framework 3.5 低版本 不支持NPOI导出插件
于 2022-06-02 17:23:54 首次发布