BUILD FAILED SAP Hybris - ant

I need to help with command "Ant clean all". I will try build one application of SAP Hybris, but, one class return de errors in to lines:
BOLDWEIGHT_BOLD cannot be resolved or is not a field
method with error:
#Override
public HSSFWorkbook createMDDExportFile(final List<JnJProductModel> products, final String fileName)
{
final String METHOD_NAME = "createMDDExportFile()";
LOGGER.info("JnJGTProductService" + Logging.HYPHEN + METHOD_NAME + Logging.HYPHEN + "Start of the method");
catalogVersionService.setSessionCatalogVersion(Jnjb2bCoreConstants.MDD_CATALOG_ID, Jnjb2bCoreConstants.ONLINE);
final String sheetName = "MDD_Products_Sheet_0";
final HSSFWorkbook excelWorkBook = new HSSFWorkbook();
final HSSFFont font = excelWorkBook.createFont();
ERROR=> font.setBoldweight(Font.BOLDWEIGHT_BOLD);
final HSSFCellStyle style = excelWorkBook.createCellStyle();
style.setFont(font);
final HSSFSheet sheet = excelWorkBook.createSheet(sheetName);
sheet.autoSizeColumn(0);
final HSSFRow downloadDateHeader = sheet.createRow(0);
downloadDateHeader.createCell(0).setCellValue("Download date");
downloadDateHeader.getCell(0).setCellStyle(style);
final String currentTime = new Date().toString();
downloadDateHeader.createCell(1).setCellValue(currentTime);
/*
* final HSSFRow globalAccounHeader = sheet.createRow(1);
* globalAccounHeader.createCell(0).setCellValue("Global Account Name");
* globalAccounHeader.getCell(0).setCellStyle(style);
* globalAccounHeader.createCell(1).setCellValue(currentAccount);
*/
try
{
final String filepath = Config.getParameter(Jnjb2bCoreConstants.EXPORT_EMAIL_ATTACHMENT_PATH_KEY) + File.separator
+ fileName;
createMDDExcelFile(products, sheet, excelWorkBook, style, filepath);
final File file = new File(filepath);
createMedia(file);
}
catch (final Exception exception)
{
LOGGER.error("There was an error while trying to create the excel file for the catalog export", exception);
}
LOGGER.info("JnJGTProductService" + Logging.HYPHEN + METHOD_NAME + Logging.HYPHEN + "End of the method");
return excelWorkBook;
}

Your maven version having issue with the one Font interface you are accessing. You imported the wrong path of Font interface.
Check your Font interface contains BOLDWEIGHT_BOLD attribute or not ?
I have my Font interface at org.apache.poi.ss.usermodel.Font location.

Related

How to read and write a xml file into the same location?

I have prepared xml files with some content and want to load it while playing on iOS device but also I want to change loaded data and serialize it in the same file again.
In Unity Editor (Windows) it works perfectly, but when I test it on iOS device it seems that I can read from StreamingAssets using WWW class, but I can't write into it.
Also I have found that I can read and write into path created by Application.persistentDataPath. But it seems that location somewhere in device and I can't put my xml into that location and users have access to that folder so that isn't good solution, isn't it?
Here code that I use to load and save the data.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
public class testxml : MonoBehaviour {
public Text result;
public InputField firstPart, secondPart;
public Toggle toggle;
private List<int> listToSave;
// Use this for initialization
void Start () {
listToSave = new List<int>();
}
public void Save()
{
Serialize();
}
public void Load()
{
StartCoroutine(Deserialize());
}
private void Serialize()
{
string path = GetPath();
try
{
Debug.Log("trying to save");
var serializer = new XmlSerializer(typeof(List<int>));
using (var fs = new FileStream(path, FileMode.OpenOrCreate))
{
serializer.Serialize(fs, listToSave);
}
}
catch (XmlException e)
{
result.text = "error";
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
Debug.LogError("xml exc while des file : " + e.Message);
}
catch (System.Exception e)
{
result.text = "error";
Debug.LogError("exc while des file : " + e.Message);
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
System.Exception exc = e.InnerException;
int i = 0;
while (exc != null)
{
Debug.Log("inner " + i + ": " + exc.Message);
i++;
exc = exc.InnerException;
}
}
}
private IEnumerator Deserialize()
{
Debug.Log("trying to load");
string path = GetPath();
var www = new WWW(path);
yield return www;
if (www.isDone && string.IsNullOrEmpty(www.error))
{
try
{
var serializer = new XmlSerializer(typeof(List<int>));
MemoryStream ms = new MemoryStream(www.bytes);
listToSave = serializer.Deserialize(ms) as List<int>;
ms.Close();
result.text += "Done\n";
foreach (var i in listToSave)
result.text += i + "\n";
}
catch (XmlException e)
{
result.text = "error";
Debug.LogError(path + " with " + (toggle.isOn?"persistent data path":"data path"));
Debug.LogError("xml exc while des file : " + e.Message);
}
catch (System.Exception e)
{
result.text = "error";
Debug.LogError("exc while des file : " + e.Message);
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
System.Exception exc = e.InnerException;
int i = 0;
while(exc!=null)
{
Debug.Log("inner "+i+": " + exc.Message);
i++;
exc = exc.InnerException;
}
}
yield break;
}
else
{
Debug.LogError("www exc while des file " + www.error);
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
yield break;
}
}
private string GetPath()
{
string path = firstPart.text;
if (toggle.isOn)
{
path += Application.persistentDataPath;
}
else
path += Application.dataPath;
path += secondPart.text;
return path;
}
}
"I want to put my xml file in this folder, and then read it. It's like default info for game"
easy, just put it in your assets. go like this...
public TextAsset myXMLFile;
in Inspector drag the file there. You're done.
"but then I also want to change that file and save"
Fair enough. What you have to do is
(1) make a path p = Application.persistentDataPath + "values.txt"
(2) program launches.
(3) check if "p" exists. if yes, read it and go to (6)
(4) IF NOT, read the textasset and save that to "p"
(5) go to point (3)
(6) you're done.
It's the only way to do it. This is indeed the normal procedure in Unity, you do it in every Unity app. There's no other way!

How to put two jasperReports in one zip file to download?

public String generateReport() {
try
{
final FacesContext facesContext = FacesContext.getCurrentInstance();
final HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + "myReport.zip\";");
final BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
final ZipOutputStream zos = new ZipOutputStream(bos);
for (final PeriodScale periodScale : Scale.getPeriodScales(this.startDate, this.endDate))
{
final JasperPrint jasperPrint = JasperFillManager.fillReport(
this.reportsPath() + File.separator + "periodicScale.jasper",
this.parameters(this.reportsPath(), periodScale.getScale(),
periodScale.getStartDate(), periodScale.getEndDate()),
new JREmptyDataSource());
final byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
response.setContentLength(bytes.length);
final ZipEntry ze = new ZipEntry("periodicScale"+ periodScale.getStartDate() + ".pdf"); // periodicScale13032015.pdf for example
zos.putNextEntry(ze);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.close();
facesContext.responseComplete();
}
catch (final Exception e)
{
e.printStackTrace();
}
return "";
}
This is my action method in the managedBean which is called by the user to print a JasperReport, but when I try to put more than one report inside the zip file it's not working.
getPeriodScales are returning two objects and JasperFillManager.fillReport is running correctly as the reports print when I just generate data for one report, when I try to stream two reports though and open in WinRar only one appears and I get an "unexpedted end of archive", in 7zip both appear but the second is corrupted.
What am I doing wrong or is there a way to stream multiple reports without zipping it?
I figured out what was, I was setting the contentLenght of the response with bytes.length size, but it should be bytes.length * Scale.getPeriodScales(this.startDate, this.endDate).size()
public JasperPrint generatePdf(long consumerNo) {
Consumer consumerByCustomerNo = consumerService.getConsumerByCustomerNo(consumerNo);
consumerList.add(consumerByCustomerNo);
BillHeaderIPOP billHeaderByConsumerNo = billHeaderService.getBillHeaderByConsumerNo(consumerNo);
Long billNo = billHeaderByConsumerNo.getBillNo();
List<BillLineItem> billLineItemByBilNo = billLineItemService.getBillLineItemByBilNo(billNo);
System.out.println(billLineItemByBilNo);
List<BillReadingLine> billReadingLineByBillNo = billReadingLineService.getBillReadingLineByBillNo(billNo);
File jrxmlFile = ResourceUtils.getFile("classpath:demo.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlFile.getAbsolutePath());
pdfContainer.setName(consumerByCustomerNo.getName());
pdfContainer.setTelephone(consumerByCustomerNo.getTelephone());
pdfContainer.setFromDate(billLineItemByBilNo.get(0).getStartDate());
pdfContainer.setToDate(billLineItemByBilNo.get(0).getEndDate());
pdfContainer.setSupplyAddress(consumerByCustomerNo.getSupplyAddress());
pdfContainer.setMeterNo(billReadingLineByBillNo.get(0).getMeterNo());
pdfContainer.setBillType(billHeaderByConsumerNo.getBillType());
pdfContainer.setReadingType(billReadingLineByBillNo.get(0).getReadingType());
pdfContainer.setLastBilledReadingInKWH(billReadingLineByBillNo.stream().filter(billReadingLine -> billReadingLine.getRegister().contains("KWH")).collect(Collectors.toList()).get(0).getLastBilledReading());
pdfContainer.setLastBilledReadingInKW(billReadingLineByBillNo.stream().filter(billReadingLine -> billReadingLine.getRegister().contains("KW")).collect(Collectors.toList()).get(0).getLastBilledReading());
pdfContainer.setReadingType(billReadingLineByBillNo.get(0).getReadingType());
pdfContainer.setRateCategory(billLineItemByBilNo.get(0).getRateCategory());
List<PdfContainer> pdfContainerList = new ArrayList<>();
pdfContainerList.add(pdfContainer);
Map<String, Object> parameters = new HashMap<>();
parameters.put("billLineItemByBilNo", billLineItemByBilNo);
parameters.put("billReadingLineByBillNo", billReadingLineByBillNo);
parameters.put("consumerList", consumerList);
parameters.put("pdfContainerList", pdfContainerList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
return jasperPrint;
}
//above code is accroding to my requirement , you just focus on the jasperPrint object which am returning , then jasperPrint object is being used for pdf generation , storing those pdf into a zip file .
#GetMapping("/batchpdf/{rangeFrom}/{rangeTo}")
public String batchPdfBill(#PathVariable("rangeFrom") long rangeFrom, #PathVariable("rangeTo") long rangeTo) throws JRException, IOException {
consumerNosInRange = consumerService.consumerNoByRange(rangeFrom, rangeTo);
String zipFilePath = "C:\\Users\\Barada\\Downloads";
FileOutputStream fos = new FileOutputStream(zipFilePath +"\\"+ rangeFrom +"-To-"+ rangeTo +"--"+ Math.random() + ".zip");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream outputStream = new ZipOutputStream(bos);
try {
for (long consumerNo : consumerNosInRange) {
JasperPrint jasperPrint = generatePdf(consumerNo);
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
outputStream.putNextEntry(new ZipEntry(consumerNo + ".pdf"));
outputStream.write(bytes, 0, bytes.length);
outputStream.closeEntry();
}
} finally {
outputStream.close();
}
return "All Bills PDF Generated.. Extract ZIP file get all Bills";
}
}

How to check-out/check-in a file into a ClearCase snapshot view using an Ant script?

I would like to update a file under ClearCase source control. This needs to happen from an Ant script.
I have created a snapshot view for this purpose. ccupdate updates it just fine.
I have tried using cccheckout but it fails with the following error cleartool: Error: To operate on UCM branch, must be set to an activity and a UCM view..
Is there a way to check-out a file in a snapshot view, replace it and check-in the new version? If this involves creating/switching to an activity, please include this in your answer.
The Apache Ant ClearCase Tasks (2003!) are pre-UCM area.
That means they have no notion of "UCM view" (snapshot or dynamic) or activities.
If you are staying with ant, you could try (not tested) a tasks library like clearantlib, which allows you to execute any cleartool command (with ccexec)
That way you can use a cleartool setact in order to set a UCM activity in the UCM view.
Your checkout will proceed only when an activity is set.
As clearantlib is only a thin wrapper around cleartool command line, you're on your own. Following some snippet of production code for the 'checkout part', that might be helpful for writing your own ant task - otherwise you need to use a bunch of ant <exec> parts calling cleartool. Checkout specific versions in a clearcase snapshotview means create and set a configspec. For the update part use ProcessBuilder with the relevant cleartool commands :
/**
*
* #param modulinfos
* #param jobid
* #param snapshotpath
*/
private void createConfSpec(ArrayList<String> modulinfos, String jobid, String snapshotpath)
{
/*
element * CHECKEDOUT
element "/at_vobt2/Foo/.../" v_1_4_00_49a
element "/at_vobt2/FooBar/.../" v_1_3_02_06c
element "/at_vobt2/Foo Base/.../" v_1_3_01_28b
element * /main/LATEST
load "/vobt2/Foo"
load "/vobt2/FooBar"
load "/vobt2/FooBase"
*/
StringBuilder sb = new StringBuilder("element * CHECKEDOUT");
for (String string : modulinfos)
{
sb.append(nl).append("element \"/" + string.split("#")[0] + "/" + string.split("#")[1] + "/.../\" " + string.split("#")[2]);
}
sb.append(nl).append("element * /main/LATEST");
for (String string : modulinfos)
{
sb.append(nl).append("load \"/" + string.split("#")[0] + "/" + string.split("#")[1] + "\"");
}
sb.append(nl);
File file = new File(snapshotpath + "\\" + jobid + ".confspec");
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(file));
writer.write(sb.toString());
writer.close();
getLogger().debug("Create ConfigSpec : " + nl + sb.toString() + "File => " + file.getPath());
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* #param snapshotpath
* #return
* #throws IOException
*/
private boolean checkSnapshotView(String snapshotpath) throws IOException
{
boolean isReady = false;
// use pushd/popd cause cmd doesn't support UNC !
ProcessBuilder pb = new ProcessBuilder
(
"cmd", "/c",
"pushd " + snapshotpath + " && cleartool lsview -l -pro -cview && popd"
);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line).append(nl);
}
isReady = !StringUtils.containsIgnoreCase(sb.toString(), "cleartool: Error: Cannot get view info for current view");
getLogger().debug("Check Snapshotview : " + snapshotpath + nl + sb.toString());
return isReady;
}
/**
*
* #param jobid
* #param snapshotpath
* #throws IOException
*/
private void createSnapshotView(String jobid, String snapshotpath) throws IOException
{
ProcessBuilder pb = new ProcessBuilder
(
"cmd", "/c",
"cleartool mkview -snapshot -tag " + "snapshot" + jobid + " " + snapshotpath
);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line).append(nl);
}
getLogger().debug("Create Snapshotview : " + nl + sb.toString());
}
/**
*
* #param snapshotpath
* #param configspecpath
* #throws IOException
*/
private void setConfigSpec(String snapshotpath, String configspecpath) throws IOException
{
// use pushd/popd cause cmd doesn't support UNC !
ProcessBuilder pb = new ProcessBuilder
(
"cmd", "/c",
"pushd " + snapshotpath + " && cleartool setcs " + configspecpath + " && popd"
);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line).append(nl);
}
getLogger().debug("Update Snapshotview : " + nl + sb.toString());
}

Crawler4j With Grails App

I am making a crawler application in Groovy on Grails. I am using Crawler4j and following this tutorial.
I created a new grails project
Put the BasicCrawlController.groovy file in controllers->package
Did not create any view because I expected on doing run-app, my crawled data would appear in my crawlStorageFolder (please correct me if my understanding is flawed)
After that I just ran the application by doing run-app but I didn't see any crawling data anywhere.
Am I right in expecting some file to be created at the crawlStorageFolder location that I have given as C:/crawl/crawler4jStorage?
Do I need to create any view for this?
If I want to invoke this crawler controller from some other view on click of a submit button of a form, can I just write <g:form name="submitWebsite" url="[controller:'BasicCrawlController ']">?
I asked this because I do not have any method in this controller, so is it the right way to invoke this controller?
My code is as follows:
//All necessary imports
public class BasicCrawlController {
static main(args) throws Exception {
String crawlStorageFolder = "C:/crawl/crawler4jStorage";
int numberOfCrawlers = 1;
//int maxDepthOfCrawling = -1; default
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setPolitenessDelay(1000);
config.setMaxPagesToFetch(100);
config.setResumableCrawling(false);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://en.wikipedia.org/wiki/Web_crawler")
controller.start(BasicCrawler.class, 1);
}
}
class BasicCrawler extends WebCrawler {
final static Pattern FILTERS = Pattern
.compile(".*(\\.(css|js|bmp|gif|jpe?g"+ "|png|tiff?|mid|mp2|mp3|mp4" +
"|wav|avi|mov|mpeg|ram|m4v|pdf" +"|rm|smil|wmv|swf|wma|zip|rar|gz))\$")
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
#Override
boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase()
!FILTERS.matcher(href).matches() && href.startsWith("http://en.wikipedia.org/wiki/Web_crawler/")
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
#Override
void visit(Page page) {
int docid = page.getWebURL().getDocid()
String url = page.getWebURL().getURL()
String domain = page.getWebURL().getDomain()
String path = page.getWebURL().getPath()
String subDomain = page.getWebURL().getSubDomain()
String parentUrl = page.getWebURL().getParentUrl()
String anchor = page.getWebURL().getAnchor()
println("Docid: ${docid} ")
println("URL: ${url} ")
println("Domain: '${domain}'")
println("Sub-domain: ' ${subDomain}'")
println("Path: '${path}'")
println("Parent page:${parentUrl} ")
println("Anchor text: ${anchor} " )
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData()
String text = htmlParseData.getText()
String html = htmlParseData.getHtml()
List<WebURL> links = htmlParseData.getOutgoingUrls()
println("Text length: " + text.length())
println("Html length: " + html.length())
println("Number of outgoing links: " + links.size())
}
Header[] responseHeaders = page.getFetchResponseHeaders()
if (responseHeaders != null) {
println("Response headers:")
for (Header header : responseHeaders) {
println("\t ${header.getName()} : ${header.getValue()}")
}
}
println("=============")
}
}
I'll try to translate your code into a Grails standard.
Use this under grails-app/controller
class BasicCrawlController {
def index() {
String crawlStorageFolder = "C:/crawl/crawler4jStorage";
int numberOfCrawlers = 1;
//int maxDepthOfCrawling = -1; default
CrawlConfig crawlConfig = new CrawlConfig();
crawlConfig.setCrawlStorageFolder(crawlStorageFolder);
crawlConfig.setPolitenessDelay(1000);
crawlConfig.setMaxPagesToFetch(100);
crawlConfig.setResumableCrawling(false);
PageFetcher pageFetcher = new PageFetcher(crawlConfig);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(crawlConfig, pageFetcher, robotstxtServer);
controller.addSeed("http://en.wikipedia.org/wiki/Web_crawler")
controller.start(BasicCrawler.class, 1);
render "done crawling"
}
}
Use this under src/groovy
class BasicCrawler extends WebCrawler {
final static Pattern FILTERS = Pattern
.compile(".*(\\.(css|js|bmp|gif|jpe?g"+ "|png|tiff?|mid|mp2|mp3|mp4" +
"|wav|avi|mov|mpeg|ram|m4v|pdf" +"|rm|smil|wmv|swf|wma|zip|rar|gz))\$")
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
#Override
boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase()
!FILTERS.matcher(href).matches() && href.startsWith("http://en.wikipedia.org/wiki/Web_crawler/")
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
#Override
void visit(Page page) {
int docid = page.getWebURL().getDocid()
String url = page.getWebURL().getURL()
String domain = page.getWebURL().getDomain()
String path = page.getWebURL().getPath()
String subDomain = page.getWebURL().getSubDomain()
String parentUrl = page.getWebURL().getParentUrl()
String anchor = page.getWebURL().getAnchor()
println("Docid: ${docid} ")
println("URL: ${url} ")
println("Domain: '${domain}'")
println("Sub-domain: ' ${subDomain}'")
println("Path: '${path}'")
println("Parent page:${parentUrl} ")
println("Anchor text: ${anchor} " )
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData()
String text = htmlParseData.getText()
String html = htmlParseData.getHtml()
List<WebURL> links = htmlParseData.getOutgoingUrls()
println("Text length: " + text.length())
println("Html length: " + html.length())
println("Number of outgoing links: " + links.size())
}
Header[] responseHeaders = page.getFetchResponseHeaders()
if (responseHeaders != null) {
println("Response headers:")
for (Header header : responseHeaders) {
println("\t ${header.getName()} : ${header.getValue()}")
}
}
println("=============")
}
}

OleDbConnection to Excel File in MOSS 2007 Shared Documents

I need to programmatically open an Excel file that is stored in a MOSS 2007 Shared Documents List. I’d like to use an OleDbConnection so that I may return the contents of the file as a DataTable. I believe this is possile since a number of articles on the Web imply this is possible. Currently my code fails when trying to initialize a new connection (oledbConn = new OleDbConnection(_connStringName); The error message is:
Format of the initialization string does not conform to specification starting at index 0.
I believe I am just not able to figure the right path to the file. Here is my code:
public DataTable GetData(string fileName, string workSheetName, string filePath)
{
// filePath == C:\inetpub\wwwroot\wss\VirtualDirectories\80\MySpWebAppName\Shared Documents\FY12_FHP_SPREADSHEET.xlsx
// Initialize global vars
_connStringName = DataSource.Conn_Excel(fileName, filePath).ToString();
_workSheetName = workSheetName;
dt = new DataTable();
//Create the connection object
if (!string.IsNullOrEmpty(_connStringName))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
oledbConn = new OleDbConnection(_connStringName);
try
{
oledbConn.Open();
//Create OleDbCommand obj and select data from worksheet GrandTotals
OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + _workSheetName + ";", oledbConn);
//create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dt);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
oledbConn.Close();
}
});
}
return dt;
}
public static OleDbConnection Conn_Excel(string ExcelFileName, string filePath)
{
// filePath == C:\inetpub\wwwroot\wss\VirtualDirectories\80\MySpWebAppName\Shared Documents\FY12_FHP_SPREADSHEET.xlsx
OleDbConnection myConn = new OleDbConnection();
myConn.ConnectionString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0");
return myConn;
}
What am I doing wrong, or is there a better way to get the Excel file contents as a DataTable?
I ended up using the open source project Excel Data Reader

Resources