■39542 / inTopicNo.3) |
Re[2]: VB.NETでExcleのコピー&ペースト |
□投稿者/ お だ (4回)-(2009/08/10(Mon) 20:26:17)
|
> 過去ログに下記内容があったんですが、解決はされてないんですよね(^^;
> .NETでExcelの値のみをコピー
> http://bbs.wankuma.com/index.cgi?mode=al2&namber=24586&KLOG=46
過去ログ見ましたが、このコードで何でダメだったんでしょうね。
VS 2008 SP1、Office 2007 ですが、下記のコードで問題無く動作しました。(C# でスイマセン)
※あくまで検証用のコードなので、解放処理は適切に実装して下さい。
以下コード
using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
Excel.Workbooks books = app.Workbooks;
Excel.Workbook book = books.Open("D:\\test.xlsx", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Sheets sheets = book.Sheets;
Excel.Worksheet sheet = sheets[1] as Excel.Worksheet;
Excel.Range cells = sheet.Cells;
Excel.Range srcRange = cells[2, 1] as Excel.Range;
srcRange.Copy(Type.Missing);
Excel.Workbook book2 = books.Add(Type.Missing);
Excel.Sheets sheets2 = book2.Sheets;
Excel.Worksheet sheet2 = sheets2[1] as Excel.Worksheet;
Excel.Range cells2 = sheet2.Cells;
Excel.Range destRange = cells2[5, 4] as Excel.Range;
destRange.PasteSpecial(Excel.XlPasteType.xlPasteValues,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,
Type.Missing, Type.Missing);
Marshal.ReleaseComObject(destRange);
Marshal.ReleaseComObject(srcRange);
Marshal.ReleaseComObject(cells);
Marshal.ReleaseComObject(cells2);
Marshal.ReleaseComObject(sheet);
Marshal.ReleaseComObject(sheet2);
Marshal.ReleaseComObject(sheets);
Marshal.ReleaseComObject(sheets2);
book.Save();
book2.SaveAs("D:\\test2.xlsx", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(book2);
books.Close();
Marshal.ReleaseComObject(books);
app.Quit();
Marshal.ReleaseComObject(app);
}
}
|
|