当前位置:首页 > Windows程序 > 正文

bool isShowExcel) { int rowsQty = dataGridView.Rows.Count;

2024-03-31 Windows程序

public static bool DataGridViewToExcel(DataGridView dataGridView, bool isShowExcel)

{

int rowsQty = dataGridView.Rows.Count;

int colsQty = dataGridView.Columns.Count;

int colIndex = 0;

if (rowsQty == 0)

{

return false;

}

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

excel.Visible = isShowExcel;

foreach (DataGridViewColumn col in dataGridView.Columns)

{

colIndex++;

excel.Cells[1, colIndex] = col.Name;

}

object[,] objData = new object[rowsQty, colsQty];

for (int r = 0; r < rowsQty; r++)

{

for (int c = 0; c < colsQty; c++)

{

objData[r, c] = dataGridView.Rows[r].Cells[c].Value;

}

}

Microsoft.Office.Interop.Excel.Range myRange;

myRange = worksheet.Range[excel.Cells[2, 1], excel.Cells[rowsQty + 1, colsQty]];

myRange.Value2 = objData;

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/36015.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494590访问次数
  • 建站天数
  • 友情链接