using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EXCEL= Microsoft.Office.Interop.Excel;
using System.Diagnostics;
namespace excel转图片
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
KillProgram();
GetExcel(@"D:\test\1.xls");
}
public static void KillProgram()
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName == "Excel") //要结束程序的名称
{
process.Kill();
}
}
}
public static string GetExcel(string excelFilePath)
{
string SaveExcelJPG = @"D:\test\1.jpg";
EXCEL.Application app = new Microsoft.Office.Interop.Excel.Application();
object objMis = Type.Missing;
EXCEL.Workbook singleExcel = app.Workbooks.Open(excelFilePath, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis, objMis);
try
{
//wsheet.UsedRange.Select();
for (int i = 1; i <= singleExcel.Worksheets.Count; i++)
{
EXCEL.Worksheet wsheet = (EXCEL.Worksheet)singleExcel.Worksheets[i];
object ranobj = DBNull.Value;
//设置选择单元格,在复制出来。
wsheet.get_Range("A1", "AA22").Copy(ranobj);
//全选单元格,全部复制出来。
//wsheet.UsedRange.Copy(objMis);
//Clipboard.SetDataObject(objMis);
IDataObject iData = Clipboard.GetDataObject();
Bitmap bits = (Bitmap)iData.GetData(DataFormats.Bitmap);
Bitmap myBitmap = new Bitmap(bits.Width, bits.Height);
Graphics g = Graphics.FromImage(myBitmap);
g.DrawImage(bits, 0, 0);
myBitmap.Save(string.Format(SaveExcelJPG, Guid.NewGuid()));
Clipboard.Clear();
myBitmap.Dispose();
bits.Dispose();
}
}
catch (Exception Excel)
{
//throw Excel;
}
finally
{
singleExcel.Close(objMis, objMis, objMis);
app.Quit();
}
return string.Empty;
}
}
}