Excel Worksheet's page setup not-working across workbook - c#

I am trying to put different data into different worksheet in the same Workbook, and each worksheet have different page setup(like header,footer,etc).
When I execute the program, the data can be successfully displayed in different worksheet, but the page setup is not working (like header and footer is missing) when I checking print preview, does anyone know the reason?
bellow is the button click event:
private void btnExportAllToExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "StockReport(ALL)_" + DateTime.Now.ToString("ddMMyyyy HHmmss") + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
Cursor = Cursors.WaitCursor; // change cursor to hourglass type
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.PrintCommunication = false;
xlexcel.ScreenUpdating = false;
xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
saveDataToSheet(xlWorkBook);
xlexcel.Calculation = XlCalculation.xlCalculationManual;
//Save the excel file under the captured location from the SaveFileDialog
xlWorkBook.SaveAs(sfd.FileName, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlexcel.DisplayAlerts = true;
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkBook);
releaseObject(xlexcel);
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvStockReport.ClearSelection();
// Open the newly saved excel file
if (File.Exists(sfd.FileName))
System.Diagnostics.Process.Start(sfd.FileName);
}
}
bellow is the code for copy data from datagridview to sheet method, and I think the problem will be here but I cannot find it:
//copy data from datagridview to clipboard and paste to excel sheet
private void saveDataToSheet(Workbook xlWorkBook)
{
int sheetNo = 1;
Worksheet xlWorkSheet = null;
bool gotData = false;
//load different data list to datagridview by changing the comboBox selected index
for (int i = 0; i <= cmbType.Items.Count - 1; i++)
{
cmbType.SelectedIndex = i;
for (int j = 0; j <= cmbSubType.Items.Count - 1; j++)
{
cmbSubType.SelectedIndex = j;
if (cmbType.Text.Equals(CMBPartHeader))
{
gotData = loadPartStockData();//if data != empty return true, else false
}
else if (cmbType.Text.Equals(CMBMaterialHeader))
{
gotData = loadMaterialStockData();//if data != empty return true, else false
}
if(gotData)//if datagridview have data
{
copyAlltoClipboard();//select all from datagridview and copy to clipboard
//create new sheet
var xlSheets = xlWorkBook.Sheets as Sheets;
var xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[sheetNo], Type.Missing, Type.Missing, Type.Missing);
xlWorkSheet = xlNewSheet;
xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(sheetNo);
xlWorkSheet.Name = cmbSubType.Text;
//Header and Footer setup
xlWorkSheet.PageSetup.LeftHeader = "&\"Calibri,Bold\"&11 " + DateTime.Now.Date.ToString("dd/MM/yyyy"); ;
xlWorkSheet.PageSetup.CenterHeader = "&\"Calibri,Bold\"&16 (" + cmbSubType.Text + ") Stock List";
xlWorkSheet.PageSetup.RightHeader = "&\"Calibri,Bold\"&11 PG -&P";
xlWorkSheet.PageSetup.CenterFooter = "Printed By " + dalUser.getUsername(MainDashboard.USER_ID);
//Page setup
xlWorkSheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4;
xlWorkSheet.PageSetup.Orientation = XlPageOrientation.xlPortrait;
xlWorkSheet.PageSetup.Zoom = false;
xlWorkSheet.PageSetup.CenterHorizontally = true;
xlWorkSheet.PageSetup.LeftMargin = 1;
xlWorkSheet.PageSetup.RightMargin = 1;
xlWorkSheet.PageSetup.FitToPagesWide = 1;
xlWorkSheet.PageSetup.FitToPagesTall = false;
xlWorkSheet.PageSetup.PrintTitleRows = "$1:$1";
// Paste clipboard results to worksheet range
xlWorkSheet.Select();
Range CR = (Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
//content edit
Range tRange = xlWorkSheet.UsedRange;
tRange.Borders.LineStyle = XlLineStyle.xlContinuous;
tRange.Borders.Weight = XlBorderWeight.xlThin;
tRange.Font.Size = 11;
tRange.EntireColumn.AutoFit();
tRange.Rows[1].interior.color = Color.FromArgb(237, 237, 237);//change first row back color to light grey
sheetNo++;
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvStockReport.ClearSelection();
releaseObject(xlWorkSheet);
}
}
}
}
I'm new here and coding as well, so if I'm doing anything wrong please let me know , thank you very much ^^

After online research and modify my code about 4 hours, now it's work!
I try to save the workbook first,
then open it for insert data to worksheet and changing the page setup.
CODE:
private void btnExportAllToExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "StockReport(ALL)_" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetFullPath(sfd.FileName);
Cursor = Cursors.WaitCursor; // change cursor to hourglass type
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.PrintCommunication = false;
xlexcel.ScreenUpdating = false;
xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
//Save the excel file under the captured location from the SaveFileDialog
xlWorkBook.SaveAs(sfd.FileName,
XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue,
XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
insertDataToSheet(path,sfd.FileName);
xlexcel.DisplayAlerts = true;
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkBook);
releaseObject(xlexcel);
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvStockReport.ClearSelection();
}
}
here is the code for insert data to worksheet method:
private void insertDataToSheet(string path, string fileName)
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
Workbook g_Workbook = excelApp.Workbooks.Open(
path,
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);
bool gotData = false;
object misValue = System.Reflection.Missing.Value;
//load different data list to datagridview but changing the comboBox selected index
for (int i = 0; i <= cmbType.Items.Count - 1; i++)
{
cmbType.SelectedIndex = i;
for (int j = 0; j <= cmbSubType.Items.Count - 1; j++)
{
cmbSubType.SelectedIndex = j;
if (cmbType.Text.Equals(CMBPartHeader))
{
gotData = loadPartStockData();//if data != empty return true, else false
}
else if (cmbType.Text.Equals(CMBMaterialHeader))
{
gotData = loadMaterialStockData();//if data != empty return true, else false
}
if (gotData)//if datagridview have data
{
Worksheet addedSheet = null;
int count = g_Workbook.Worksheets.Count;
addedSheet = g_Workbook.Worksheets.Add(Type.Missing,
g_Workbook.Worksheets[count], Type.Missing, Type.Missing);
addedSheet.Name = cmbSubType.Text;
addedSheet.PageSetup.LeftHeader = "&\"Calibri,Bold\"&11 " + DateTime.Now.Date.ToString("dd/MM/yyyy"); ;
addedSheet.PageSetup.CenterHeader = "&\"Calibri,Bold\"&16 (" + cmbSubType.Text + ") STOCK LIST";
addedSheet.PageSetup.RightHeader = "&\"Calibri,Bold\"&11 PG -&P";
addedSheet.PageSetup.CenterFooter = "Printed By " + dalUser.getUsername(MainDashboard.USER_ID);
//Page setup
addedSheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4;
addedSheet.PageSetup.Orientation = XlPageOrientation.xlPortrait;
addedSheet.PageSetup.Zoom = false;
addedSheet.PageSetup.CenterHorizontally = true;
addedSheet.PageSetup.LeftMargin = 1;
addedSheet.PageSetup.RightMargin = 1;
addedSheet.PageSetup.FitToPagesWide = 1;
addedSheet.PageSetup.FitToPagesTall = false;
addedSheet.PageSetup.PrintTitleRows = "$1:$1";
copyAlltoClipboard();
addedSheet.Select();
Range CR = (Range)addedSheet.Cells[1, 1];
CR.Select();
addedSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
Range tRange = addedSheet.UsedRange;
tRange.Borders.LineStyle = XlLineStyle.xlContinuous;
tRange.Borders.Weight = XlBorderWeight.xlThin;
tRange.Font.Size = 11;
tRange.EntireColumn.AutoFit();
tRange.Rows[1].interior.color = Color.FromArgb(237, 237, 237);//change first row back color to light grey
Clipboard.Clear();
dgvStockReport.ClearSelection();
}
}
}
g_Workbook.Worksheets.Item[1].Delete();
g_Workbook.Save();
}

Related

C# Datatable linq condiction check

I have created the function shown below. Everything is working fine, the challenge now, is that I have some scenarios where it would be ideal to have the constructor 'RadGridView grid' as a Datatable. I'm looking for a constructor that can take the input type of 'RadGridView' or type of 'Datatable' - a kind of "universal" constructor, if that is possiple?
public static void Export(RadGridView grid, string sheetName)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel file |*.xlsx";
saveFileDialog1.Title = "Save";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = sheetName;
Microsoft.Office.Interop.Excel.Range aRange = worksheet.UsedRange;
workbook.Worksheets[1].Cells.NumberFormat = "#";
for (int i = 1; i < grid.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = grid.Columns[i - 1].HeaderText;
}
for (int i = 0; i < grid.Rows.Count; i++)
{
for (int j = 0; j < grid.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = grid.Rows[i].Cells[j].Value.ToString();
}
}
aRange.Value = aRange.Value;
aRange.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
worksheet.Columns.AutoFit();
workbook.SaveAs(saveFileDialog1.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();
}
}
Thanks in advance!
I solved this by using the 'dynamic' keyword.

Loop through Excel files and copy correct range in a separate file with C#

Intro:
Today I have decided to make an Excel automatization task with C#. This is probably the first time I am doing something like this, thus the problems are plenty.
The task:
Pretty much, the idea is the following - I have 4 excel files in folder strPath. I have to loop through all of them and make a file called Report.xlsx in the same folder, with the information from those files.
The information, that I need is anything, below row 9. Thus, the first row to copy is row number 10. That is why, the first file I loop for is saved as Report, and the bMakeOnce value is changed. After the first file is looped and saved As, I start entering into the else condition. There I locate the last used row of the XL files and I try to copy the range into the sheetReport.
The questions:
First of all - any ideas for code improvement;
Whenever I am looping through the files I get the following picture telling me that each of the looping file is opened already.
Any good idea how to do the range copy better? Currently, I simply try to put the copied range on every 200+n line, to avoid some confusion for me.
Any idea why I do not get anything in the sheetReport, except for the first file?
The code I am using (initially, for the current goto Github below):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class MainClass
{
static void Main()
{
string strPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), #"..\..\..\"));
string[] strFiles = Directory.GetFiles(strPath);
Excel.Application excel = null;
bool bMakeOnce = true;
int intFirstLine = 10;
int intLastColumn = 50;
int lastRow;
int lastRowReport;
Excel.Workbook wkbReport = null;
string strWkbReportPath;
int n = 0;
foreach (string strFile in strFiles)
{
Console.WriteLine(strFile);
Excel.Workbook wkb = null;
Excel.Worksheet sheet = null;
Excel.Worksheet sheetReport = null;
Excel.Range rngLast = null;
Excel.Range rngLastReport = null;
Excel.Range rngToCopy = null;
Excel.Range rngDestination = null;
excel = new Excel.Application();
excel.Visible = true;
wkb = OpenBook(excel, strFile);
if (bMakeOnce)
{
bMakeOnce = false;
strWkbReportPath = wkb.Path + "\\" + "Report.xlsx";
wkb.SaveAs(strWkbReportPath);
wkbReport = OpenBook(excel, strWkbReportPath);
}
else
{
wkb = OpenBook(excel, strFile);
sheetReport = wkbReport.Worksheets[1];
sheet = wkb.Worksheets[1];
n++;
rngLastReport = sheetReport.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
rngLast = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
rngToCopy = sheet.Range[sheet.Cells[intFirstLine, 1], sheet.Cells[rngLast.Row, intLastColumn]];
int size = rngToCopy.Rows.Count;
Console.WriteLine(size);
rngDestination = sheetReport.Range[sheetReport.Cells[200 * n, 1], sheetReport.Cells[200 * n + size, intLastColumn]];
rngToCopy.Copy(rngDestination);
//rngDestination.PasteSpecial(Excel.XlPasteType.xlPasteAll);
}
}
wkbReport.Close(false);
excel.Quit();
}
public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly = false, bool editable = true, bool updateLinks = true)
{
Excel.Workbook book = excelInstance.Workbooks.Open(
fileName, updateLinks, readOnly,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
return book;
}
}
Now it works somehow, producing what I want:
using System;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
class MainClass
{
static void Main()
{
string strPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), #"..\..\..\"));
string[] strFiles = Directory.GetFiles(strPath);
Excel.Application excel = null;
bool bMakeOnce = true;
string strReportName = "Report.xlsx";
int intFirstLine = 10;
int intLastColumn = 50;
int lastRow;
int lastRowReport;
int intTotalRows;
Excel.Workbook wkbReport = null;
string strWkbReportPath;
int n = 0;
excel = new Excel.Application();
excel.Visible = true;
foreach (string strFile in strFiles)
{
if (strFile.Contains(strReportName))
{
Console.WriteLine(strReportName + " is deleted.");
File.Delete(strFile);
}
}
foreach (string strFile in strFiles)
{
if (strFile.Contains(strReportName))
{
continue;
}
Console.WriteLine(strFile);
Excel.Workbook wkb = null;
Excel.Worksheet sheet = null;
Excel.Worksheet sheetReport = null;
Excel.Range rngLastReport = null;
Excel.Range rngToCopy = null;
wkb = Open(excel, strFile);
if (bMakeOnce)
{
bMakeOnce = false;
strWkbReportPath = wkb.Path + "\\" + strReportName;
wkb.SaveAs(strWkbReportPath);
wkb.Close();
wkbReport = Open(excel, strWkbReportPath);
}
else
{
sheetReport = wkbReport.Worksheets[1];
sheet = wkb.Worksheets[1];
//lastRow = sheet.Cells[1, 3].get_End(Excel.XlDirection.xlUp).Row;
intTotalRows = sheet.Rows.Count;
lastRow = sheet.Cells[intTotalRows, 1].End(Excel.XlDirection.xlUp).Row;
lastRowReport = sheetReport.Cells[intTotalRows, 1].End(Excel.XlDirection.xlUp).Row;
//lastRowReport = sheetReport.Cells[intTotalRows, 1].get_End(Excel.XlDirection.xlUp).Row;
//lastRowReport = sheetReport.Cells[intTotalRows, intTotalRows.End[Excel.XlDirection.xlUp]].Row;
n++;
rngToCopy = sheet.Range[sheet.Cells[intFirstLine,1],sheet.Cells[lastRow, intLastColumn]];
int size = rngToCopy.Rows.Count;
rngLastReport = sheetReport.Range[sheetReport.Cells[lastRowReport+1, 1], sheetReport.Cells[lastRowReport + 1+size, intLastColumn]];
rngToCopy.Copy(rngLastReport);
wkb.Close(false);
}
}
wkbReport.Close(true);
excel.Quit();
Console.WriteLine("Finished!");
}
public static Excel.Workbook Open(Excel.Application excelInstance, string fileName, bool readOnly = false, bool editable = true, bool updateLinks = true)
{
Excel.Workbook book = excelInstance.Workbooks.Open(
fileName, updateLinks, readOnly,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
return book;
}
//public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly = false, bool editable = true, bool updateLinks = true)
//{
// Excel.Workbook book = excelInstance.Workbooks.Open(
// fileName, updateLinks, readOnly,
// Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
// Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
// Type.Missing, Type.Missing);
// return book;
//}
}
Thus, I have put it codeReview here: https://codereview.stackexchange.com/questions/153054/loop-through-excel-files-and-copy-correct-range-in-a-separate-file

DataGridView To Excel With Colored Cells

I looked a lots of example and demo but I could not to it.
I'm trying to convert datagridview to excel.
My Results
http://i.imgur.com/ujvGiXX.png
But its convert to excel like this
http://i.imgur.com/0OXkUkL.png
I want to copy cells size and color but how?
I convert to excel with this code
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = listBox1.SelectedItem.ToString() + " " + listBox3.SelectedItem.ToString() + " Stok Reçeteleri" + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
//ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
//xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.X
FileInfo fileInfo = new FileInfo(sfd.FileName);
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
update the internal loop to be:
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
Range range = (Range)xlWorkSheet.Cells[i + 1, j + 1];
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(dataGridView1.Rows[i].DefaultCellStyle.BackColor );
}
}
don't forget:
using Microsoft.Office.Interop.Excel;
see: Change the background of Cells with C#
Try this code for exporting to excel instead of what you are using. I use this for web apps though.
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "SomeFileName" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}

save as dialog box for exporting file to excel C#

I am exporting multiple datatable as different worksheets to a single excel file and it is working fine. However, the excel file is saved to the path specified. I want a save as dialog from where the user can select the path to save the file. I have tried the following code on button click:
protected void excelexport(object sender, EventArgs e)
{
try
{
string sql = null;
string data = null;
string path = "C:\\inetpub/wwwroot/MahindraEarth/exportexcel/exportexcel";
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataTable dts = new System.Data.DataTable(); ;
System.Data.DataTable dss = new System.Data.DataTable();
Enquiry gs = new Enquiry();
ResultClass objres = gs.fn_GetEnquiryList();
if (objres.bStatus)
{
eslist<Enquiry> OBJLIST = objres.objData as eslist<Enquiry>;
if (OBJLIST.Count > 0)
{
dt = (DataTable)OBJLIST;
}
}
Operator op = new Operator();
ResultClass objrest = op.fn_GetOperatorList();
if (objrest.bStatus)
{
eslist<Operator> OBJLISTS = objrest.objData as eslist<Operator>;
if (OBJLISTS.Count > 0)
{
dts = (DataTable)OBJLISTS;
}
}
Contact co = new Contact();
ResultClass objress = co.fn_GetContactList();
if (objress.bStatus)
{
eslist<Contact> OBJLISS = objress.objData as eslist<Contact>;
if (OBJLISS.Count > 0)
{
dss = (DataTable)OBJLISS;
}
}
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt);
dataSet.Tables.Add(dts);
dataSet.Tables.Add(dss);
SaveFileDialog saveFileDialog = new SaveFileDialog();
String[] Worksheets = new String[dataSet.Tables.Count];
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[dataSet.Tables.Count];
for (int k = 0; k < dataSet.Tables.Count; k++)
{
DataTable dst = dataSet.Tables[k];
xlWorkSheet[k] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(k + 1);
for (i = 0; i <= dst.Rows.Count - 1; i++)
{
for (j = 0; j <= dst.Columns.Count - 1; j++)
{
xlWorkSheet[k].Cells[1, j + 1] = dataSet.Tables[k].Columns[j].ColumnName;
data = dst.Rows[i].ItemArray[j].ToString();
xlWorkSheet[k].Cells[i + 2, j + 1] = data;
xlWorkSheet[k].Name = dataSet.Tables[k].TableName;
}
}
}
xlWorkBook.SaveAs(path + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
for (int p = 0; p < 3; p++)
{
releaseObject(xlWorkSheet[p]);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
exportsuccess.Style.Add("display", "");
}
catch (Exception ex)
{
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
How to get the save as dialog box in order to save the multiple datatables in multiple worksheet and not as a single sheet.
Thanks,
give this a try. This should give you the Save As dialog box. Some of the code should look similar to yours, which should give you an idea as to where this code excerpt should be attached.
#region Save & Quit
//Save and quit, use SaveCopyAs since SaveAs does not always work
Guid id = Guid.NewGuid();
string uniqueFileName = id.ToString() + ".xls";
string fileName = Server.MapPath("~/" + uniqueFileName);
xlApp.DisplayAlerts = false; //Supress overwrite request
xlWorkBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
//Release objects
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
//Give the user the option to save the copy of the file anywhere they desire
String FilePath = Server.MapPath("~/" + uniqueFileName);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=MyClaimsReport-" + DateTime.Now.ToShortDateString() + ".xls;");
response.TransmitFile(FilePath);
response.Flush();
response.Close();
//Delete the temporary file
DeleteFile(fileName);
#endregion
private void DeleteFile(string fileName)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch (Exception ex)
{
//Could not delete the file, wait and try again
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(fileName);
}
catch
{
//Could not delete the file still
}
}
}
}

Insert Array into Excel Cell

I want to insert an Array of characters into one column of Excel. I normally use something like this to just add a normal string:
lCommand.CommandText += "\"" + row["source"].ToString().Replace("\"", "\"\"").Replace(" ", " ") + "\",";
How would I add an Array of strings to a Column of Excel? Thanks!
See this article:
Fun with Excel--setting a range of cells via an array
I recommend that you read the (short) article, but as a spoiler:
Excel.Range r = this.Range["B2", "B4"];
object[,] workingValues = new object[3, 1];
for (int i = 0; i < 3; i++)
{
workingValues[i, 0] = i + 2; // 2,3,4
}
r.Value2 = workingValues;
You can open the File with C# and write to the cell you want.
First :
using Microsoft.Office.Interop.Excel;
This require you to have COM reference for Excel.
After this you need to open the file you want and set the value. After, you can close the file.
Here is an example. You can always loop for each rows or column for your array.
_Application docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = false;
docExcel.DisplayAlerts = false;
_Workbook workbooksExcel = docExcel.Workbooks.Open(#"C:\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);
_Worksheet worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
((Range)worksheetExcel.Cells["1", "A"]).Value2 = "aa";
((Range)worksheetExcel.Cells["1", "B"]).Value2 = "bb";
workbooksExcel.Save();
workbooksExcel.Close(false, Type.Missing, Type.Missing);
docExcel.Application.DisplayAlerts = true;
docExcel.Application.Quit();
Edit:
You can use the Dynamic keyword if you do not want all those Type.Missing parameter :
_Application docExcel = new Application{Visible = false};
dynamic workbooksExcel = docExcel.Workbooks.Open(#"C:\test.xlsx");
var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
((Range)worksheetExcel.Cells["1", "A"]).Value2 = "test1";
((Range)worksheetExcel.Cells["1", "B"]).Value2 = "test2";
workbooksExcel.Save();
workbooksExcel.Close(false);
docExcel.Application.Quit();

Categories

Resources