ERP Export

private void Export_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog();
file.DefaultExt = "xls ";
file.Filter = "Execl files (*.xls)|*.xls";
if (file.ShowDialog() == DialogResult.OK)
{

Excel.Application app = new Excel.Application();

try
{
if (app == null)
{
return;
}

app.Visible = true;
//Excel.Workbooks workbooks = app.Workbooks;
//Excel._Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//Excel.Sheets sheets = workbook.Worksheets;
//Excel._Worksheet worksheet = (Excel._Worksheet)sheets.get_Item(1);
Excel.Workbook workbook = app.Application.Workbooks.Open(@"D:AllenProjectsERPERPinRelease est1.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);


if (worksheet == null)
{
return;
}
string sLen = "";
//取得最后一列列名
char H = (char)(64 + dataGridView1.ColumnCount / 26);
char L = (char)(64 + dataGridView1.ColumnCount % 26);
if (dataGridView1.ColumnCount < 26)
{
sLen = L.ToString();
}
else
{
sLen = H.ToString() + L.ToString();
}


//标题
string sTmp = sLen + "1";
Excel.Range ranCaption = worksheet.get_Range(sTmp, "A1");
string[] asCaption = new string[dataGridView1.ColumnCount];
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
asCaption[i] = dataGridView1.Columns[i].HeaderText;
}
ranCaption.Value2 = asCaption;

//数据
object[] obj = new object[dataGridView1.Columns.Count];
for (int r = 0; r < dataGridView1.RowCount - 1; r++)
{
for (int l = 0; l < dataGridView1.Columns.Count; l++)
{
if (dataGridView1[l, r].ValueType == typeof(DateTime))
{
obj[l] = dataGridView1[l, r].Value.ToString();
}
else
{
obj[l] = dataGridView1[l, r].Value;
}
}
string cell1 = sLen + ((int)(r + 2)).ToString();
string cell2 = "A" + ((int)(r + 2)).ToString();
Excel.Range ran = worksheet.get_Range(cell1, cell2);
ran.Value2 = obj;
}
//保存
workbook.SaveCopyAs(file.FileName);
workbook.Saved = true;

}
finally
{
//关闭
app.UserControl = false;
app.Quit();
app = null;
}
}
}

原文地址:https://www.cnblogs.com/xiao-hei/p/8317997.html