نوشته شده توسط
babahooman
با سلام
اولا اگر این مبحث جایی توی این سایت بحث شده ممنون میشم لینکشو بذارید من هرچی گشتم نتونستم پیدا کنم.
من میخوام برنامه ای بنویسم که دو ستون از اکسل یا تکست بگیره و فایل هایی که نامشون در ستون اول هست رو به ستون دوم تغییر بده مثلا:
نام قدیم |
نام جدید |
old1.jpg |
new1.jpg |
old2.jpg |
new2.jpg |
old3.jpg |
new3.jpg |
میخوام فایل هایی که اسمشون old1.jpg و old2.jpg و old3.jpg هست رو به new1.jpg و new2.jpg و new3.jpg تغییر بده
با تشکر از تمامی اساتید.
قطعه کد زیر رو نوشتم ولی جواب نمیده کجاش رو اشتباه کردم؟
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComO bject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
xlWorkBook = xlApp.Workbooks.Open(Application.StartupPath + "\\Book1.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindow s, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1) ;
range = xlWorkSheet.UsedRange;
for (int columnCounter = 1; columnCounter <= range.Columns.Count; columnCounter++)
{
this.dataGridView1.Columns.Add(xlWorkSheet.Cells[1, columnCounter].Value2, xlWorkSheet.Cells[1, columnCounter].Value2);
}
//get the value of each excel cell and put into this variable
string str;
//Loop counters
int rowCounter = 0;
int columnCounter2 = 0;
for (rowCounter = 2; rowCounter <= range.Rows.Count; rowCounter++)
{
//Create a new row into the datagridview
this.dataGridView1.Rows.Add();
for (columnCounter2 = 1; columnCounter2 <= range.Columns.Count; columnCounter2++)
{
str = Convert.ToString((range.Cells[rowCounter, columnCounter2] as Excel.Range).Value2);
//add the value of excel file into the new row
this.dataGridView1.Rows[rowCounter - 2].Cells[columnCounter2 - 1].Value = str;
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 1; i < dataGridView1.RowCount; i++)
{
try
{
File.Move(dataGridView1[0,i] + ".jpg", dataGridView1[1, i].Value.ToString() + ".jpg");
}
catch (Exception)
{
}
}
}
}
}