public static void ExportExcel(DataGridView dgv)
{ try
{
int lvA = 0;
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (dgv.Columns[i].Visible)
{
lvA++;
}
}
int rowCount = dgv.RowCount;
int columnCount = lvA;
Microsoft.Office.Interop.Excel.Application exc = new Microsoft.Office.Interop.Excel.Application();
if (exc == null)
{
throw new Exception("Excel无法启动");
}
exc.Visible = true;
Workbooks workbooks = exc.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = exc.Sheets;
_Worksheet worksheet = (_Worksheet)sheets[1];
if (worksheet == null)
{
throw new Exception("Worksheet error");
}
Range r = worksheet.get_Range("A1", Missing.Value);
if (r == null)
{
MessageBox.Show("Range无法启动");
throw new Exception("Range error");
}
//以上是一些例行的初始化工作,下面进行具体的信息填充
//填充标题
int ColIndex = 1;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Columns[i].Visible)
{
worksheet.Cells[1, ColIndex++] = dgv.Columns[i].HeaderText;
}
}
//获取DataGridView中的所有行和列的数值,填充到一个二维数组中.
object[,] myData = new object[rowCount + 1, columnCount];
for (int j = 0; j < dgv.Rows.Count; j++)
{
int a = 0;
for (int k = 0; k < dgv.Columns.Count; k++)
{
if (k > 0)
{
if (dgv.Rows[j].Cells[k].Visible)
{
a++;
myData[j, a] = dgv[k, j].Value;
}
}
else if (dgv.Rows[j].Cells[k].Visible)
{
myData[j, a] = dgv[k, j].Value;
}
}
}
//将填充好的二维数组填充到Excel对象中.
r = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[rowCount + 1, columnCount]);
r.Value2 = myData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void Print(DataGridView dataGridView1)
{
try
{
int RCount = dataGridView1.Rows.Count;
int CCount = dataGridView1.Columns.Count;
if (RCount <= 0 || CCount <= 0)
{
MessageBox.Show(