I have worked on a lot of things in Excel using C#.Net. In this blog, I will give information about how to move one excel file into another. This is a Windows Application, built in VS2008.
Now the question arises that what is the need to copy one excel file to other. The need is that firstly I don’t want the original copy to be affected. Secondly, if in the original copy there are rows or columns whose text is hidden, like shown below:
then the complete data should be visible. Next thing is adding a new sheet that can be said as Summary page or Index page. This new sheet consists hyperlink of each sheet. i.e. name of all the sheets and a link provided so that one can easily shuffle from main sheet to any other sheet.
Lets, start with the code now:
Following are the namespaces to be added:
#region Imports
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 System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
#endregion
It is always a best practice to add a region. Clarity of code is seen through this. Next step is adding the required variables that will be used globally. Following is the region for the same.
#region Variable Declaration
Excel.Application xlexcel;
Excel.Workbook xlWorkBook;
Excel.Workbook xlWorkBookNew;
Excel.Sheets worksheets;
Excel.Worksheet newSheet = null;
ArrayList arrCellData = new ArrayList();
ArrayList arrBackGround = new ArrayList();
bool flag = false;
#endregion
Now in the design page, take a label, a text box, 2 buttons, 1 progress bar.
Place it as below given image:
Label :
Name – lblChooseFile, Value – Choose File
TextBox :
Name – txtBrowse, Value – empty
Button :
Name – btnBrowse, Value – Browse
Name – txtExportToExcel, Value – Export To Excel
ProgressBar :
Name – progressBar1, Value – empty
#region Events
public frmExportData()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{ }
private void btnBrowse_Click(object sender, EventArgs e)
{
BrowseExcelFile();
}
private void txtExportToExcel_Click(object sender, EventArgs e)
{
if (txtBrowse.Text == "")
{
MessageBox.Show("Please choose a file to export data.");
txtBrowse.Focus();
}
else
{
try
{
//~~> name of the newly created file
xlexcel = new Excel.Application();
//~~> Open a File
xlWorkBook = xlexcel.Workbooks.Open(txtBrowse.Text, 0, true, 5, "", "", false,
Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
//~~> Set your worksheets
worksheets = xlWorkBook.Worksheets;
//~~> Adding New Sheet
newSheet = (Excel.Worksheet)worksheets.Add(worksheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "Index";
newSheet.Cells[3, 1] = "*Click on the links to go to detail sheet.";
newSheet.get_Range("A3", "A3").Font.Color = System.Drawing.ColorTranslator.ToOle(Color.FromName("Red"));
int i = 0;
int pBar = 0;
progressBar1.Minimum = 0;
foreach (Excel.Worksheet xlsheet in worksheets)
{
progressBar1.Maximum = worksheets.Count;
if (progressBar1.Value < worksheets.Count - 1)
{
pBar = pBar + 1;
progressBar1.Value = pBar;
}
Excel.Range selectedRange = (Excel.Range)xlsheet.UsedRange;
selectedRange.EntireColumn.AutoFit();
selectedRange.EntireRow.AutoFit();
char letter = 'A';
foreach (Excel.Range row in selectedRange.Rows)
{
CopyExcel(row, xlsheet);
if (xlsheet.Name != "Index" && arrCellData.Count > 0)
{
for (int j = 0; j < arrCellData.Count; j++)
{
int cellno = 5 + i;
if (j == 0)
{
Excel.Range rangeToHoldData = newSheet.get_Range("A" + cellno, "A" + cellno);
newSheet.Hyperlinks.Add(rangeToHoldData, "", "'" + xlsheet.Name + "'!A1", "", arrCellData[j].ToString());
}
else
{
letter = Convert.ToChar(letter + 1);
newSheet.Cells[cellno, j + 1] = arrCellData[j].ToString();
newSheet.get_Range(letter.ToString() + cellno, letter.ToString() + cellno).Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.FromName(arrBackGround[j].ToString()));
}
}
i = i + 2;
flag = false;
arrCellData.Clear();
arrBackGround.Clear();
}
}
}
foreach (Excel.Worksheet xlsheet in worksheets)
{
if (xlsheet.Name == "Index")
{
AdjustNewSheetStyle(xlsheet);
break;
}
}
progressBar1.Value = progressBar1.Maximum;
//~~>Copy it. This will create a new Excel file with selected sheets
worksheets.Copy(Missing.Value, Missing.Value);
xlWorkBookNew = xlexcel.ActiveWorkbook;
//~~> Save the new workbook
string strSavePath = SaveExcelFile();
xlWorkBookNew.SaveAs(strSavePath, Excel.XlFileFormat.xlOpenXMLWorkbook,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//~~> Close
xlWorkBookNew.Close(true, Missing.Value, Missing.Value);
xlWorkBook.Close(false, Missing.Value, Missing.Value);
xlexcel.Quit();
//~~> Cleanup
ReleaseObject(worksheets);
ReleaseObject(xlWorkBookNew);
ReleaseObject(xlWorkBook);
ReleaseObject(xlexcel);
//~~> Notify User
MessageBox.Show("Excel File Created.");
//~~> Exit App
Application.Exit();
}
catch (Exception ex)
{ }
progressBar1.Value = 0;
txtBrowse.Text = "";
}
}
#endregion
#region User Defined Functions
/// <summary>
/// Copy Data from one Excel to another
/// </summary>
/// <param name="row"></param>
/// <param name="xlsheet"></param>
private void CopyExcel(Excel.Range row, Excel.Worksheet xlsheet)
{
int cellCount = row.Cells.Count;
int counter = 0;
double RowHeightLargest = 0;
foreach (Excel.Range cell in row.Cells)
{
counter = counter + 1;
//~~> Gets CellData
string cellData = cell.Text.ToString();
if (cellData != "")
{
try
{
if (flag == true)
{
arrCellData.Add(cellData);
Color getColor = Color.Transparent;
if (cellData == "Green")
{
getColor = Color.YellowGreen;
}
else if (cellData == "Red")
{
getColor = Color.Red;
}
else if (cellData == "Amber")
{
getColor = Color.Orange;
}
arrBackGround.Add(getColor.Name);
}
if (cellData == "Index")
{
flag = true;
}
//Adjust Cell Height and Width
((Excel.Range)xlsheet.Cells[cell.Row, cell.Column]).Font.Size = 10;
((Excel.Range)xlsheet.Cells[cell.Row, cell.Column]).Font.Name = "Arial";
float fontSize = 10;
string fontName = "Arial";
cellData = cellData.Replace("\n", "");
double height = EstimateSize(cellData, fontName, fontSize);
if (RowHeightLargest < height)
{
if (height < 15)
{
cell.RowHeight = 15;
}
else if ((double)cell.RowHeight > height)
{
cell.RowHeight = (double)cell.RowHeight;
RowHeightLargest = (double)cell.RowHeight;
}
else if (height > 409)
{
RowHeightLargest = 408;
cell.RowHeight = 408;
}
else
{
RowHeightLargest = height;
cell.RowHeight = height;
}
}
}
catch (Exception ex)
{ }
}
if (counter == cellCount)
{
break;
}
}
}
/// <summary>
/// Adjust Excel Style of New Sheet
/// </summary>
/// <param name="xlsheet"></param>
private void AdjustNewSheetStyle(Excel.Worksheet xlsheet)
{
Excel.Range selectedRange = (Excel.Range)xlsheet.UsedRange;
selectedRange.EntireColumn.AutoFit();
selectedRange.EntireColumn.ColumnWidth = 40;
selectedRange.EntireRow.AutoFit();
double RowHeightLargest = 0;
foreach (Excel.Range cell in selectedRange.Rows.Cells)
{
//~~> Gets CellData
string cellData = cell.Text.ToString();
if (cellData != "")
{
try
{
//Adjust Cell Height and Width
float fontSize = Convert.ToSingle(((Excel.Range)xlsheet.Cells[cell.Row, cell.Column]).Font.Size.ToString());
string fontName = ((Excel.Range)xlsheet.Cells[cell.Row, cell.Column]).Font.Name.ToString();
cellData = cellData.Replace("\n", "");
double height = EstimateSize(cellData, fontName, fontSize);
if (RowHeightLargest < height)
{
if (height < 15)
{
cell.RowHeight = 25;
cell.ColumnWidth = 25;
}
else if ((double)cell.RowHeight > height)
{
cell.RowHeight = (double)cell.RowHeight;
RowHeightLargest = (double)cell.RowHeight;
cell.ColumnWidth = 40;
}
else if (height > 409)
{
RowHeightLargest = 408;
cell.RowHeight = 408;
cell.ColumnWidth = 60;
}
else
{
RowHeightLargest = height;
cell.RowHeight = height;
cell.ColumnWidth = 40;
}
}
}
catch (Exception ex)
{ }
}
else
{
cell.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
}
}
selectedRange.WrapText = true;
selectedRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
selectedRange.Borders.Color = System.Drawing.ColorTranslator.ToOle(Color.Black);
}
/// <summary>
/// Clean Up Code
/// </summary>
/// <param name="obj"></param>
private void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
/// <summary>
/// Browse Excel File Code
/// </summary>
private void BrowseExcelFile()
{
OpenFileDialog browseFile = new OpenFileDialog();
browseFile.Filter = "Excel files (*.xls or *.xlsx)|*.xls;*.xlsx";
browseFile.Title = "Browse Excel file";
if (browseFile.ShowDialog() == DialogResult.Cancel)
return;
try
{
txtBrowse.Text = browseFile.FileName;
}
catch (Exception)
{
MessageBox.Show("Error opening file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
/// <summary>
/// Save Excel File Code
/// </summary>
/// <returns></returns>
private string SaveExcelFile()
{
SaveFileDialog savefile2 = new SaveFileDialog
{
InitialDirectory = @"C:\Program Files\Folder\",
Filter = "Excel files (*.xls or *.xlsx)|*.xlsx;*.xls",
FilterIndex = 1,
FileName = "*.xlsx",
Title = "Save File",
OverwritePrompt = true
};
string strPath = "";
if (savefile2.ShowDialog() == DialogResult.OK)
{
strPath = savefile2.FileName;
}
return strPath;
}
/// <summary>
/// Estimated size of a cell in excel file
/// </summary>
/// <param name="text"></param>
/// <param name="fontName"></param>
/// <param name="fontSize"></param>
/// <returns></returns>
private double EstimateSize(string text, string fontName, float fontSize)
{
using (Bitmap i = new Bitmap(100, 100))
{
using (Graphics g = Graphics.FromImage(i))
{
using (Font f = new Font(fontName, fontSize))
{
return .06 * g.MeasureString(text.ToString(), f).Width;
}
}
}
}
#endregion