using System.IO;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
public bool OpenExcelInSpreadSheet()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
openFileDialog.Title = "选择要打开的文件";
openFileDialog.ShowDialog();
if (openFileDialog.FileName.Length > 0)
{
//将原文件拷贝一份到临时文件夹再打开备份文件,不推荐直接打开原文件,因为有可能该文件已经被打开了。
//也不推荐将excel文件转换成xml文件再用spreadsheet打开,因为有的版本的excel格式转换到xml后不能正确打开。
//本例临时文件夹为应用程序所在目录的“temp excel files”文件夹。
string path = System.Windows.Forms.Application.ExecutablePath;
FileInfo exeInfo = new FileInfo(path);
path = exeInfo.DirectoryName + "\\";
string tempExcel = path + "temp excel files\\" + openFileDialog.FileName.Split(new Char[] { '\\' }).Last();
if (File.Exists(tempExcel))
{
string just_name = ofd.FileName.Split(new Char[] { '\\' }).Last();
DialogResult result = MessageBox.Show(just_name + "已经存在,确认覆盖?", "文件上传提示", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
File.Copy(ofd.FileName, tempExcel, true);
Excel.Application app = new Excel.Application();
if (app == null)
{
MessageBox.Show("Excel打开失败!");
return false;
}
app.Visible = false;
app.UserControl = true;
Excel.Workbooks workbooks = app.Workbooks;
Excel._Workbook workbook = workbooks.Open(newFileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null);
app.DisplayAlerts = false;
try
{
app.CopyObjectsWithCells = true;
Excel._Worksheet sheet1 = (Excel._Worksheet)workbook.Sheets[1]; //打开sheet1
sheet1.UsedRange.Copy(Type.Missing); //复制sheet1到剪贴板
AxMicrosoft.Office.Interop.Owc11.AxSpreadsheet spreadsheet = new AxMicrosoft.Office.Interop.Owc11.AxSpreadsheet();
spreadsheet.get_Range(this.spreadsheet.Cells[1, 1]).Paste(); //将剪贴板复制的内容贴到spreadsheet上
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return false;
}
app.Quit();
File.Delete(tempExcel);
return true;
}else
{
return false;
}
}
}
}