Winfrom导出DataGridView数据到Excel中 怎么在C#写代码控制Excel单元格的长度自动填充数据呢?
2013-07-26
展开全部
SaveFileDialog sfdg = new SaveFileDialog();
sfdg.DefaultExt = "xls";
sfdg.Filter = "Excel文件(*.xls)|*.xls";
sfdg.RestoreDirectory = true;
sfdg.CreatePrompt = true;
sfdg.Title = "导出Excel到"; //DataTable dt = db.gettab("select * from sell");
if (sfdg.ShowDialog() == DialogResult.OK)
{
try
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();//建立Excel对象
excel.Application.Workbooks.Add(true); for (int j = 0; j < dataGridView1.ColumnCount; j++)
{ excel.Cells[1, j + 1] = dataGridView1.Columns[j].HeaderText;
}
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int x = 0; x < dataGridView1.ColumnCount; x++)
{
if (dataGridView1[x, i].Value != null)
{
if (dataGridView1[x, i].ValueType == typeof(string))
{
excel.Cells[i + 2, x + 1] = "'" + dataGridView1[x, i].Value.ToString();
}
else
{
excel.Cells[i + 2, x + 1] = dataGridView1[x, i].Value.ToString();
}
}
}
} excel.Visible = true;
excel.ExtendList = false;
excel.ActiveWorkbook.SaveAs(sfdg.FileName, Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Quit(); MessageBox.Show("导出Excel成功!");
excel = null;
GC.Collect();
} catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
finally
{
GC.Collect();
}
sfdg.DefaultExt = "xls";
sfdg.Filter = "Excel文件(*.xls)|*.xls";
sfdg.RestoreDirectory = true;
sfdg.CreatePrompt = true;
sfdg.Title = "导出Excel到"; //DataTable dt = db.gettab("select * from sell");
if (sfdg.ShowDialog() == DialogResult.OK)
{
try
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();//建立Excel对象
excel.Application.Workbooks.Add(true); for (int j = 0; j < dataGridView1.ColumnCount; j++)
{ excel.Cells[1, j + 1] = dataGridView1.Columns[j].HeaderText;
}
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int x = 0; x < dataGridView1.ColumnCount; x++)
{
if (dataGridView1[x, i].Value != null)
{
if (dataGridView1[x, i].ValueType == typeof(string))
{
excel.Cells[i + 2, x + 1] = "'" + dataGridView1[x, i].Value.ToString();
}
else
{
excel.Cells[i + 2, x + 1] = dataGridView1[x, i].Value.ToString();
}
}
}
} excel.Visible = true;
excel.ExtendList = false;
excel.ActiveWorkbook.SaveAs(sfdg.FileName, Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Quit(); MessageBox.Show("导出Excel成功!");
excel = null;
GC.Collect();
} catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
finally
{
GC.Collect();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询